如何更轻松地将 += 与 jQuery 选择器一起使用?

发布于 2024-10-02 13:29:09 字数 607 浏览 1 评论 0原文

我从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

山有枢 2024-10-09 13:29:09

对于 jQuery,您可以使用 append 代替。

您的 $('#js').innerHTML += ' – this was inserted using JavaScript'; 可以与 [0] 一起使用,例如:

$('#js')[0].innerHTML += ' – this was inserted using JavaScript';
//      ^^^--- here

...因为你可以通过这种方式访问​​原始 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.:

$('#js')[0].innerHTML += ' – this was inserted using JavaScript';
//      ^^^--- here

...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.)

想你只要分分秒秒 2024-10-09 13:29:09
$('#js').append(' – this was inserted using JavaScript');
$('#js').append(' – this was inserted using JavaScript');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文