我有一张 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(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");
});
});
关于javascript - 无法从 jquery 每个循环中添加样式类或访问元素的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30573137/