如何获得上一段和下一段 [英] How to get previous and next paragraph

查看:101
本文介绍了如何获得上一段和下一段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在JS中开发一个TaskPane插件。我想从包含游标的段落中获取指定数量的前一段和下一段。即使我遍历整个文档的段落(我想避免),这些段落也没有任何
ID。 

I'm developing a TaskPane plugin in JS. I'd like to get specified number of previous and next paragraphs from a paragraph containing a cursor. Even if I iterate over the entire document's paragraphs (which I'd like to avoid), the paragraphs don't have any IDs. 

有人能指出我正确的方向?

Could someone point me into the right directions?

谢谢

推荐答案

嗨petrsimon,

Hi petrsimon,

>>段落没有任何ID

>> the paragraphs don't have any IDs

我们可以获得ID,但这些ID是根据段落项目。选定的段落ID与正文中段落中的ID不同。我们可以比较文本以找到当前的ID。

We could get ids, but these ids are according to the paragraphs items. The selected paragraph id will not the same as the id in the paragraphs in the body. We could compare the text to find the current id.

这是一个简单的代码:

Here is a simple code:

//get current paragraph
    function current() {
        Word.run(function (context) {
            //get current paragraph
            var r = context.document.getSelection();
            return context.sync().then(
                function () {
                    var p = r.paragraphs;
                    context.load(p,'text');
                    return context.sync().then(function () {
                        var currentParagraph = p.items[p.items.length - 1];
                        //var currentText = currentParagraph.text;
                        previous(currentParagraph);
                        return context.sync().then(function () {                         
                               console.log('previous paragraph selected');
                        });
                    });
                }
                );            
        });
    }
    function previous(para) {
        Word.run(function (context) {
            //get all paragraphs
            var paragraphs = context.document.body.paragraphs;
            context.load(paragraphs, 'text');
            return context.sync().then(function () {
                paragraphs.items.forEach(function (element) {
                    //compare text to find the current paragraph
                    if (element.text == para.text)
                    {
                        //get current previous id
                        var previousId = element.m__Id - 1;
                        //select the previous paragraph by id
                        paragraphs.items[previousId].select();
                    }
                });
                return context.sync().then(function () {
                    console.log('previous paragraph selected');
                });
            });
        });
    }

最好的问候,

Best Regards,

Edward


这篇关于如何获得上一段和下一段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆