我想在 jQuery 中更改表格的图标,但我无法找到该元素并更改它的背景。我正在使用 jQuery 的树表库。
这是我的 jQuery 代码:
Factory.query().$promise.then(function(data) {
$rootScope.tree = data;
console.log($rootScope.tree);
buildTreeTable($rootScope.tree);
})
function buildTreeTable(tree){
$("#example").treetable({
expandable: true,
onNodeExpand: nodeExpand,
onNodeCollapse: nodeCollapse
});
function nodeExpand () {
getNode(this.id);
}
function nodeCollapse () {
console.log("Collapsed: " + this.id);
}
$("#example tbody").on("mousedown", "tr", function() {
$(".selected").not(this).removeClass("selected");
$(this).toggleClass("selected");
});
var len = tree.length;
for(var i = 0; i < len; i++){
if (tree[i].status == 1){
var print = $('#example').attr('class').find('a').css("background-image","url(../../images/image.png)");
console.log("Status is 1. Load icon for 1", print);
}
}
这是我的 html:
<div class="panel-body">
<table id="example">
<tbody>
<thead>
<tr>
<th >Tree data</th>
<th>Header1</th>
<th>Header2</th>
</tr>
</thead>
</tbody>
</table>
</div>
我想更改 <td>
的图标取决于我从我的数据库中得到什么,这意味着如果状态为 1,我加载一个背景图像,如果状态为 2,我加载另一个。
我的<td>
元素包含 <span>
和 <a>
标签,我想更改 <a>
的背景图片标签。我怎样才能在 jQuery
中实现这一点? ?
这是页面加载后我的元素:
这是我得到的错误:
TypeError: $(...).attr(...).find is not a function
编辑:
这段代码是我尝试为每个 tr 加载单独图标的方式
function changeIcon(data){
for(var i = 0; i < data.length; i++){
if (data[i].status == 0){
$('tr span.icon').each(function(){
$(this).addClass('status');
})
console.log("Status is 0. Load icon for 0");
}else if(data[i].status == 1){
console.log("Status is 1. Load icon for 1");
}else if(data[i].status == 2){
console.log("Status is 2. Load icon for 2");
}else
console.log("Status is 3. Load icon for 3");
}
提前致谢!
最佳答案
你得到这个错误是因为你有一个不必要的 .attr('class')
在你的 jQuery 链中。
.attr('name')
返回具有您为其提供的名称的属性的值。所以你写的将返回 class
的值HTML 元素上的属性,它不会继续 jQuery 链。 <table id="example">
没有class
属性,因此返回值将为 undefined
.然后,您将尝试在链上运行更多 jQuery 方法,例如 .find()
但是undefined
不是 jQuery 对象,你不能那样做。
将您的行更改为:
$('#example').find('a').css("background-image","url(../../images/image.png)");
第二个问题是你的for循环需要在你的.then()
里面成功处理函数。否则,它将立即运行,而不是在 AJAX 调用完成后运行。
Factory.query().$promise.then(function(data) {
$rootScope.tree = data;
console.log($rootScope.tree);
buildTreeTable($rootScope.tree);
// put your background image code here
$('#example').find('a').css("background-image","url(../../images/image.png)")
})
第三,您应该了解 jQuery 选择器的工作原理,因为您的选择总是会找到每个 <a>
。整个表格内的标记。
关于javascript - 使用 jQuery 更改表格的图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45027117/