简体   繁体   English

通过jQuery用它的索引替换html元素

[英]Replace an html element with it's index via jQuery

I'm trying to replace an HTML element i get via it's index, I'm trying this but it won't work: 我正在尝试替换我通过它的索引获取的HTML element ,我正在尝试这个但它不起作用:

<div class="results">
    <div id="61">Result 1 content</div>
    <div id="8762">Result 2 content</div>
    <div id="234">Result 3 content</div>
</div>

<script>
    var index = 0;
    var html = '<div id="243">Result 1 content</div>';
    var element = $('.results').get(index);
    element.replaceWith(html);
</script>

how can I replace an entire HTML element by getting it by it's index ? 如何通过它的index来替换整个HTML element

$('.results div').eq(index).replaceWith(html);

Fiddle 小提琴

You should use .eq() to filter the set of matched elements inside a jQuery object by its index. 您应该使用.eq()通过索引过滤jQuery对象内的匹配元素集。 Also $('.results') only has 1 element (itself). 另外$('.results')只有1个元素(本身)。 I assume you're looking for the div s inside of it. 我假设你正在寻找里面的div


Also if you have div s inside of your div s, use the more specific child selector : 此外,如果您的div内部有div ,请使用更具体的子选择器

$('.results > div').eq(index).replaceWith(html);

Which has the same effect as using the .children method with a selector filter: 这与使用带有选择器过滤器的.children方法具有相同的效果:

$('.results').children(':eq(' + index + ')').replaceWith(html);

Or more simply, concatenating it all in a single selector: 或者更简单地说,在一个选择器中将它连接起来:

$('.results > div:eq(' + index + ')').replaceWith(html);

Fiddle 小提琴

There are many other ways to get this done with jQuery, but these should be more than enough. 还有很多其他方法可以通过jQuery完成这项工作,但这些方法应该足够了。 =]

.get retrieves the DOM element at the index. .get检索索引处的DOM元素。 What you're looking for is .eq 你要找的是.eq

var index = 0
$($('.results div')[index]).replaceWith('<div id="243">Result 1 content</div>')
var element = $('.results').find('div');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM