如何更轻松地将 += 与 jQuery 选择器一起使用?
我从 JS Bin 中获取了以下示例:
HTML
<p id='js'>Hello, World!</p>`
JavaScript
document.getElementById('js').innerHTML += ' – this was inserted using JavaScript';`
现在,我想对 jQuery 执行相同的操作。由于我找不到将 += 与 jQuery 选择器一起使用的方法(否则我不会问这个问题),这是一个很长的方法:
var js = $('#js').html() + ' – this was inserted using JavaScript';
$('#js').html(js);
我使用 jQuery 因为它的语法更短更简单。但这两个代码的长度几乎相同。
这不起作用:
$('#js').innerHTML += ' – this was inserted using JavaScript';
I've taken the following example from JS Bin:
HTML
<p id='js'>Hello, World!</p>`
JavaScript
document.getElementById('js').innerHTML += ' – this was inserted using JavaScript';`
Now, I'd like to do the same with jQuery. Since I couldn't find a way to use += with jQuery selectors (otherwise I wouldn't ask this question), here is the long way:
var js = $('#js').html() + ' – this was inserted using JavaScript';
$('#js').html(js);
I use jQuery because it's syntax is shorter and simpler. But these two codes have almost the same length.
This does not work:
$('#js').innerHTML += ' – this was inserted using JavaScript';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于 jQuery,您可以使用
append
代替。您的
$('#js').innerHTML += ' – this was inserted using JavaScript';
可以与[0]
一起使用,例如:...因为你可以通过这种方式访问原始 DOM 元素。但是通过
innerHTML
附加内容是一个坏主意,因为它使浏览器工作非常困难:首先它必须循环遍历其内部 DOM 等效项,将其序列化为 HTML 字符串,然后必须重新 -完成+=
后解释新的 HTML。 (当然,后者会非常非常快,因为将 HTML 渲染到其内部结构中是浏览器所做的,并且它们对此进行了高度优化,但前者可能不会一点也不快。)With jQuery, you can use
append
instead.Your
$('#js').innerHTML += ' – this was inserted using JavaScript';
would work with a[0]
, though, e.g.:...because you can access the raw DOM element that way. But it's a bad idea to append content via
innerHTML
because it makes the browser work really hard: First it has to loop through its internal DOM equivalent, serializing it into an HTML string, then it has to re-interpret the new HTML after you've done your+=
. (Granted the latter will be really, really fast because rendering HTML into their internal structures is what browsers do and they're highly optimized for it, but the former may not be fast at all.)