我有一个带表的变量:
var tableCode='<table><tr><td><span class'thisone'>'the_text_to_change'</span><span class'thisone'>'other_text_to_change'</span><span class'thisone'>'another_text_to_change'</span></td></tr></table>'
我想用“thisone”类替换每个span内的文本,每个都取决于类中的值。
因此变量tableCode应为:
var tableCode='<table><tr><td><span class'thisone'>'the_text_changed_1'</span><span class'thisone'>'the_text_changed_2'</span><span class'thisone'>'the_text_changed_3'</span></td></tr></table>'
我一直在阅读每个文档:https://api.jquery.com/each/,但它是针对DOM而不是Javascript中的变量。
所以:读取变量,抛出它并检测具有特定css类的跨度,并根据文本更改值。
非常感谢!!!
答案 0 :(得分:1)
单程
var tableCode = "<table><tr><td><span class='thisone'>'the_text_to_change'</span><span class='thisone'>'other_text_to_change'</span><span class='thisone'>'another_text_to_change'</span></td></tr></table>";
tableCode = $(tableCode); //make it a jQuery Object
tableCode.find('span.thisone').text(function (i) {
return 'the_text_to_change_' + ++i;
}); //find span with class thisone and set text
console.log(tableCode.html()); //to retrieve the changed string use tableCode.html()
答案 1 :(得分:0)
这样做:
var jqueryObj=$("<table><tr><td><span class='thisone'>'the_text_to_change'</span><span class='thisone'>'other_text_to_change'</span><span class='thisone'>'another_text_to_change'</span></td></tr></table>");
jqueryObj.find('span').each(function(){
$(this).text($(this).attr("class"));
});