![](/img/trans.png)
[英]How can I combine JQuery selectors and variables to shorten code for easier scaleability?
[英]How can I use += with jQuery selectors easier?
我從JS Bin中獲取了以下示例:
<p id='js'>Hello, World!</p>`
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';
$('#js').append(' – this was inserted using JavaScript');
使用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呈現到其內部結構是瀏覽器的工作,並且瀏覽器對此進行了高度優化,但前者可能根本不夠快。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.