jQuery 将文本附加到属性而不是替换它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/644898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append text to an attribute rather than replacing it?
提问by gravitation
I want to append some text to the title attribute of all elements of a certain class.
我想在某个类的所有元素的 title 属性中附加一些文本。
回答by Kharisma Wijaya
I know this question is 7 years old. Just in case someone came across this question, here's the solution without using .each:
我知道这个问题已经有 7 年的历史了。以防万一有人遇到这个问题,这里是不使用 .each 的解决方案:
$('.theclass').attr("title", function() { return $(this).attr("title") + "Appended text." });
回答by strager
回答by Seth Battis
JQuery has come a ways. There's a version of .attr()that takes a function as the value argument:
JQuery 有办法。有一个版本的.attr()将函数作为值参数:
$('.theclass').attr('title', (i, value) => `${value || ""}appended text`);
i
is the index of the attribute, value
is the current value of the attribute... which might not be set, hence the value || ""
expression, to avoid converting undefined
into the string 'Undefined'
uglily.
i
是属性的索引,是属性value
的当前值......可能没有设置,因此是value || ""
表达式,以避免转换undefined
为'Undefined'
丑陋的字符串。