[英]Appending text to the inner HTML
I've seen the following syntax in pre-existing code. 我已经在预先存在的代码中看到了以下语法。
$("#offers").children().last().html(
$("#offers").children().last().html() + "!");
Is there a smoother approach to append some text to the HTML? 有没有更平滑的方法将一些文本附加到HTML? Is there also a nicer way to refactor the following?
还有一种更好的方法来重构以下内容吗?
$("#offers").children().last().html(
"!" + $("#offers").children().last().html());
And how about this? 那呢?
$("#offers").children().last().html(
"!" + $("#offers").children().last().html() + "!");
My suggestion is the following but I'd like to see if there's something even neater. 我的建议如下,但我想看看是否有更整洁的东西。
var old = $("#offers").children().last().html();
var prefix = "";
var suffix = "";
$("#offers").children().last().html(suffix + old + prefix));
You can use prepend and append 您可以使用前置和附加
$('#offers').children().last().prepend("!");
$('#offers').children().last().append("!");
You can do this: 你可以这样做:
$("#offers").children().last().html(function(index, oldHtml){
return oldHtml + '!';
});
or as per your suggestion: 或根据您的建议:
var prefix = "!";
var suffix = "!";
$("#offers").children().last().html(function(index, oldHtml){
return suffix + oldHtml + prefix;
});
You can simply use ".append()" method provided by jQuery. 您可以简单地使用jQuery提供的“ .append()”方法。 ( Api append() )
( Api append() )
Try: 尝试:
$("#offers").children().last().append("!");
try something like this 尝试这样的事情
// Simply remove one time from DOM.
var elem = $("#offers").children().last();
var old_html = elem.html();
var prefix = "";
var suffix = "";
elem.html( suffix + old_html + prefix);
You can fetch the DOM object with jQuery.get()
method and use good old innerHTML
: 您可以使用
jQuery.get()
方法获取DOM对象,并使用良好的旧innerHTML
:
$("#offers").children().last().get(0).innerHTML += "!";
Or you can use jQuery.append()
或者您可以使用
jQuery.append()
$("#offers").children().last().append('!');
In the second case use jQuery.prepend()
在第二种情况下,使用
jQuery.prepend()
$("#offers").children().last().prepend('!');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.