我正在使用ajax获取外部文件的内容,然后从字符串中获取一个元素,然后使用jQuery的find()将其加载到页面上的元素中。这很好用,但是现在我需要从外部文件中获取一个元素和另一个元素之间的所有内容,我尝试使用.nextUntil(),但是它并没有停留在正确的元素上,而是在捕获其余的所有内容。文献。所以问题是,我可以这样做吗,还是我应该采取另一种方式呢?

...
success: function(result) {
     html = $(result),
         comp = $(html).find("#comp1").nextUntil(".comp-close");
     $('.output-text').html(comp);
},
...

最佳答案

您的问题可能是“ .comp-close”不是直接同级。

我在这里验证了此行为:

<div id="1"></div>
<p>1</p>
<p>2</p>
<p>3</p>
<div>
  <p>4</p>
  <div id="2"></div>
  <p>5</p>
</div>
<div id="3"></div>
<p>6</p>

<p>=====</p>
<div id="4"></div>




// Clones until the end of the document
//var list = $('#1').nextUntil("#2");

// Clones until #3 since it is a direct sibling
var list = $('#1').nextUntil("#3");

console.log(list)

// Clone if you do not want to remove the originals from the DOM
$('#4').append(list.clone());




JSFiddle

另请注意,如果您不想修改DOM,则应使用clone()。

希望这对您有所帮助!

关于javascript - jQuery .find和.nextUntil一起,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35488296/

10-11 12:54