无法在每个循环中添加样式 class 或从 jquery 访问元素的属性

Unable to add style class or access elements' attributes from jquery each loop

我有一个 table,它看起来像这样:

<table id="ctoTable" class="table table-bordered">
<thead> ... </thead>
<tbody>
    <tr></tr>
    <tr id="kpi#1" class="js-editable"></tr>
    <tr id="kpi#2" class="js-editable"></tr>
    <tr id="kpi#3" class="js-editable"></tr>
    <tr id="kpi#4" class="js-editable"></tr>
    <tr id="kpi#5" class="js-editable"></tr>
    <tr id="kpi#6" class="js-editable"></tr>
    <tr id="kpi#7" class="js-editable"></tr>
    <tr id="kpi#8" class="js-editable"></tr>
    <tr id="kpi#9" class="js-editable"></tr>
    <tr id="kpi#76" class="js-editable"></tr>
    <tr id="kpi#77" class="js-editable"></tr>
    <tr></tr>
</tbody>

我想制作某种过滤器,允许我显示和隐藏一些行。我很确定我可以用这种方式做到这一点,但不幸的是它不起作用。不仅我无法 add/remove 类,我甚至无法获得 th.

的属性
jQuery(document).ready(function($) {
    $( "#hideRows" ).click(function() {
        var rows = $('.js-editable');
        $.each(rows, function(index, item) {
            console.log(item);
            //item.addClass("hideElement"); //try to add the class to the tr
            console.log(item.attr("id")); //try to print tr id in console
        });
    });
});

因此只有第一行会被打印出来

<tr id="kpi#1" class="js-editable"></tr> 

并且该方法在没有记录任何错误的情况下中断。 有人可以向我解释这里发生了什么,我该如何解决这个问题。

问题是 item 循环内部是 dom 元素引用而不是 jQuery 对象,因此您无法直接从 [=12] 访问 jQuery 方法=].

相反,您需要将 item 的 jQuery 对象引用传递给 jQuery,例如 $(item),然后您可以使用 jQuery 方法喜欢

jQuery(document).ready(function ($) {
    $("#hideRows").click(function () {
        var rows = $('.js-editable');
        rows.each(function (index, item) {
            console.log(item);
            //$(item).addClass("hideElement"); //try to add the class to the tr
            console.log($(item).attr("id")); //try to print tr id in console
        });
    });
});

但是如果你只想添加一个 class 则不需要使用循环

jQuery(document).ready(function ($) {
    $("#hideRows").click(function () {
        var rows = $('.js-editable');
        rows.addClass("hideElement");
    });
});

另请注意,最好使用 .each() instead of $.each() 遍历 jQuery 对象。

如果你写 item.attr,它会 return 一个错误,因为这样 item 不是 jQuery 对象。

改成这样:

$(item).attr("id")

console.log($(item).attr("id")) 而不是 console.log(item.attr("id"))

jQuery(document).ready(function($) {
    $( "#hideRows" ).click(function() {
        var rows = $('.js-editable');
        $.each(rows, function(index, item) {
            console.log(item);
            //item.addClass("hideElement"); //try to add the class to the tr
            console.log($(item).attr("id")); //try to print tr id in console
        });
    });
});  

DEMO