JavaScript للحصول على الفقرة القادمة من النص المحدد في صفحة الويب

StackOverflow https://stackoverflow.com/questions/4332307

سؤال

مرحبًا ، أريد أن أحصل على وظيفة للحصول على فقرة من النص المحدد.

هذه هي الوظيفة للحصول على الفقرة الحالية من النص المحدد

function getSelected() {
  var userSelection;
  if (window.getSelection) {
      selection = window.getSelection();
  } else if (document.selection) {
      selection = document.selection.createRange();
  }
  var parent = selection.anchorNode;
  parent = parent.parentNode;
  alert(parent.innerHTML);

}

كيف يمكنني الحصول على الفقرة الناتجة التالية من النص المحدد في صفحة الويب. إذا كان لدي وظيفة للحصول على الفقرة الحالية أعلاه. (أعتقد أن استخدام Nextsibling ولكني لا أعرف تنفيذه في الكود أعلاه) هل يمكنك مساعدتي؟

-شكرا لك-

هل كانت مفيدة؟

المحلول

يمكنك استخدام Previousibling و nextsibling للحصول على المعلمات.

لغة البرمجة:

<p> This is 1st paragraph</p>
<p> This is 2nd paragraph</p>
<p> This is 3rd paragraph</p>
<a href="javascript:void(0)" onclick="getSelected(-1)">Prev</a>
<a href="javascript:void(0)" onclick="getSelected(1)">Next</a>

JavaScript:

function getSelected(direction) {
  var userSelection;
  if (window.getSelection) {
      selection = window.getSelection();
  } else if (document.selection) {
      selection = document.selection.createRange();
  }
  var parent = selection.anchorNode;
  parent = parent.parentNode;
  if(direction == -1){
    var prevEle = parent.previousSibling;
    while(prevEle.nodeType!=1){
        prevEle = prevEle.previousSibling;
    }
    alert(prevEle.innerHTML);
  }else {
    var nextEle = parent.nextSibling ;
    while(nextEle.nodeType!=1){
        nextEle = nextEle.nextSibling;
    }
    alert(nextEle.innerHTML);
  }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top