首页 > JQurey选择器,如何选中父下的兄弟元素

JQurey选择器,如何选中父下的兄弟元素



<div class="video_items"> <div class="record_name"></div> <div class="postdate">发表于 3天前</div> <div class="edit" style="display: block;"><input type="checkbox" id="edit_item" name="options[]" value="90"> </div> </div> <div class="video_items"> <div class="record_name"></div> <div class="postdate">发表于 3天前</div> <div class="edit" style="display: block;"><input type="checkbox" id="edit_item" name="options[]" value="90"> </div> </div> <div class="video_items"> <div class="record_name"></div> <div class="postdate">发表于 3天前</div> <div class="edit" style="display: block;"><input type="checkbox" id="edit_item" name="options[]" value="90"> </div> </div>
<script type="text/javascript">
$(document).ready(function(){
$("#edit_item").click(
function(){
$(this).parent().parent().find('.record_name').css('text-decoration','line-through');
});
});
</script>

现在js代码只对第一个#edit_item生效,点其他#edit_item时无效果。
请问哪里搞错了呢?


那个……在同一个页面里,相同的 ID 只能存在一个……您用错了,这不关 jQuery 的事儿。


jQuery 文档有详细说明:

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. 

如果希望对多个 DOM 元素起作用,例如你举的例子,可以这样写:

$(document).ready(function(){
  $(".edit").click(
  function(){
    $(this).parent().parent().find('.record_name').css('text-decoration','line-through');
  });
});

.closest('.video_items').find('.record_name')这样就直接找到

【热门文章】
【热门文章】