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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:30:22  来源:igfitidea点击:

Append text to an attribute rather than replacing it?

jquery

提问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

In that context, $(this)is not the element of $('.theclass'). Maybe you want to use each:

在这种情况下,$(this)不是 的元素$('.theclass')。也许你想使用each

$('.theclass').each(function() {
    $(this).attr("title", $(this).attr("title") + "Appended text.");
});

回答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`);

iis the index of the attribute, valueis the current value of the attribute... which might not be set, hence the value || ""expression, to avoid converting undefinedinto the string 'Undefined'uglily.

i是属性的索引,是属性value的当前值......可能没有设置,因此是value || ""表达式,以避免转换undefined'Undefined'丑陋的字符串。