我很难找出为什么这段代码不起作用。具体来说,为什么我不能跨越变量,然后给它添加一个类?当然,如果它只是文本而不是变量,我会成功添加类。:
var fruit = 'bananas';
var paragraph = $('<div></div>');
paragraph.html('I like ' + '<span class="features">'fruit'</span>');
$(".features").css("color","yellow");
最佳答案
我可以看出您的代码有几处错误。
// fruit var is fine
var fruit = 'bananas';
// originally you had html markup in here, but you have to use html selectors.
var paragraph = $('div');
// you were close here but you didnt have plus symbols either side of your fruit var
paragraph.html('I like '+'<span class="features">'+fruit+'</span>');
// add the colour to your .features span - this is fine
$(".features").css("color","yellow");
请参阅此处的工作 fiddle 。 https://jsfiddle.net/joshmoto/k0vrs8ne/
关于javascript - 如何将 span 标记添加到 .html Jquery 方法中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52917041/