简体   繁体   English

如何在jQuery选择器中更轻松地使用+ =?

[英]How can I use += with jQuery selectors easier?

I've taken the following example from JS Bin: 我从JS Bin中获取了以下示例:

HTML 的HTML

<p id='js'>Hello, World!</p>`

JavaScript 的JavaScript

document.getElementById('js').innerHTML += ' – this was inserted using JavaScript';`

Now, I'd like to do the same with jQuery. 现在,我想对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: 由于我找不到在jQuery选择器上使用+ =的方法(否则我不会问这个问题),这是很长的路要走:

var js = $('#js').html() + ' – this was inserted using JavaScript';
$('#js').html(js);

I use jQuery because it's syntax is shorter and simpler. 我使用jQuery,因为它的语法更短,更简单。 But these two codes have almost the same length. 但是,这两个代码的长度几乎相同。

This does not work: 这不起作用:

$('#js').innerHTML += ' – this was inserted using JavaScript';
$('#js').append(' – this was inserted using JavaScript');

With jQuery, you can use append instead. 使用jQuery,您可以改用append

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

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

...because you can access the raw DOM element that way. ...因为您可以通过这种方式访问​​原始DOM元素。 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 += . 但是,通过innerHTML附加内容是一个坏主意,因为它会使浏览器非常难工作:首先,它必须循​​环遍历其内部DOM,将其序列化为HTML字符串,然后必须在您输入以下内容后重新解释新的HTML。已经完成了+= (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.) (授予后者确实非常快,因为将HTML呈现到其内部结构是浏览器的工作,并且浏览器对此进行了高度优化,但前者可能根本不够快。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM