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

标签 javascript jquery html html-table

我有一张 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>

我想制作某种过滤器,允许我显示和隐藏一些行。我很确定我可以用这种方式做到这一点,但不幸的是它不起作用。不仅我无法添加/删除类,我什至无法获取 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 对象,所以你不能直接从 item 访问 jQuery 方法。

相反,您需要像 $(item) 这样将 item 传递给 jQuery 来获取它的 jQuery 对象引用,然后您可以使用像

这样的 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
        });
    });
});

但是如果你只是想添加一个类就没有必要使用循环

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

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

关于javascript - 无法从 jquery 每个循环中添加样式类或访问元素的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30573137/

相关文章:

javascript - 尝试播放另一个嵌入式youtube视频时弹出弹出模式的jquery

javascript - 不支持 Service Worker 的缓存清除

javascript - 扩展 MultiSelect 小部件会破坏 MVVM 中的值绑定(bind)

javascript - 更改div的高度获取另一个div的高度

javascript - D3 CSV 导入 "%"

javascript - 如何使用 angularjs sanitize 安全地保留 html 颜色

jquery - Bootstrap 3 的分割按钮插入符高度小于主按钮

javascript - 一个极其奇怪的 Javascript 行为 : onLoad and $(document). ready()

html - 如何使用应用程序开发 API 将动态 html 或脚本添加到 Bigcommerce 商店中的任何页面

javascript - Backbone、TypeScript 和 super