gpt4 book ai didi

jquery - 如何将字符串转换为 Jquery 中的可访问属性以使功能动态化

转载 作者:行者123 更新时间:2023-11-30 08:41:07 25 4
gpt4 key购买 nike

我想让我的 JavaScript 函数变成动态的并且更灵活。

实际上,我有一个表,其中有一组行,每一行都有一组列。其中,某些列可能包含 id 属性和 anchor 标记,而其他列可能不包含。找到下面的示例表。

 <table id="history-data">
<tr>
<td id="264"> <a class="add-icon"><img src="/includes/images/plusCircle.png"></a></td>
<td class="tdata">10/09/2014</td>
<td class="tdata">09:25 AM</td>
<td class="historyData"><a class="sess-invite-link">Invite</a></td>
</tr>

<tr>
<td id="264"> <a class="add-icon"><img src="/includes/images/plusCircle.png"></a></td>
<td class="tdata">10/09/2014</td>
<td class="tdata">09:25 AM</td>
<td class="historyData"><a class="sess-invite-link">Invite</a></td>
</tr>
</table>

现在我想遍历表行并获取特定的列属性。例如,对于第一列,我需要获取 id,对于第二列,我需要获取其内部文本,对于最后一列,我需要获取 anchor 数据。

我生成了脚本以使其运行良好。但我想让它动态化,因为将来可能会再添加两列,并且需要访问列内的子元素。

这是我的 JavaScript 函数:

// Get the table row objects
var tableRow = $('#history-data > tbody > tr');

// List out the properties that need to be accessed.
var arr = ["attr('id')","html()","html()","find('a').html()"];

// Loop through the rows and access the properties
for(var r = 0; r < tableRow.length; r++){
$(tableRow[r]).children().each(function(index) {
console.log(arr[index]);
console.log($(this).arr[index]); // fuzzy area
});
}

在 JQuery 中是否有可能将字符串转换为可访问的属性?

提前致谢。

最佳答案

通常,将字符串转换为代码并不是一个好主意。为什么不直接使用函数数组?

var funcs = [   function($elem) { 
return $elem.attr('id')
},

function($elem) {
return $elem.html()
}
// ... etc.
];

tableRows.each(function() {

$(this).children().each(function(i) {

console.log( funcs[i]($(this)) );

});

});

关于jquery - 如何将字符串转换为 Jquery 中的可访问属性以使功能动态化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26276975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com