简体   繁体   中英

How to use += operator

Since I started using JQuery ive always wondering how does this operator work in JQuery Example:

for(var i = 0;i<=4;i++)
{
document.getElementById("mydiv").innerText += i;//<- works as expected
}

//results will be 0,1,2,3,4

but if i use JQuery instead i dont know how to do it

for(var i = 0;i<=4;i++)
{
$("mydiv").text(+i)//<- NO!
$("mydiv").text+(i)//<- NO!
$("mydiv").+text(i)//<- JAJA COME ON!
$("mydiv").text(i)+//<- I guess that was stupid


}

This isn't possible like this. Unlike innerText , text() is a method, not a property.

Try:

$("mydiv").text($("mydiv").text() + i);

Or if you'd rather not make 2 references to $("mydiv") you can do:

$("mydiv").text(function(i,v){
   return v + i; 
});

You just need to work with jQuery here. Use the text method to extract the value, and then call it again to set the new value:

for(var i = 0;i<=4;i++)
{
    var mydiv = $("mydiv"),
        t = mydiv.text();
    mydiv.text(t + i);
}

You can't use such shorcuts for jQuery methods, it only works for native assignment operators . For jQuery .text() , use a callback:

$("#mydiv").text(function(index, oldtext) {
    return oldtext + i;
});

This callback thing works for all jQuery property "assignments", be it .html , .val , .prop , .attr , .css , or .text .

jQuery is not a programming language but a library built upon javascript, so, the rules are exactly the same as those you have to follow using javascript, and javascript has not been designed to understand these kinds of structures.


Edit

Of course I mean om(+1) does not increment op while o.p++ and o.p+=1 does :

var o = {};
o.p = 1;
o.m = function () { return this.p; };
o.m(+1); // o.p equals 1
o.p++;   // o.p equals 2
o.p+=1;  // o.p equals 3

Like other answers point out, jQuery is just a framework and is subject to same syntactic rules as any JavaScript code.

While I see the advantage of passing in a function to .text() , I don't think it's a general purpose approach to solve your real problem : how to concatenate text when you use a function instead of a variable.

I'd favor the usage of Array.join() for efficient concatenation:

var textParts = [ $("mydiv").text() ];
for(var i = 0;i<=4;i++)
{
    textParts[textParts.length] = i;
}
$("mydiv").text(textParts.join(',')) // result: '...,1,2,3,4'

If you prefer the function approach over a loop, you could also use Array.map() .

AFAIK DOM functions are rather slow so it's more effective to do the concatenation first and then set the div node value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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