jquery each selector doesnt work

家住魔仙堡 提交于 2019-12-24 10:39:16

问题


I created a counter that count different numbers each, but when I choose all the elemnts in class it doesnt work...

$(document).ready(function() {


    function change() {
        /*
        $(".test").each(function(i,domeElement){

            var theNum = parseInt(this.html())+1;
            this.html(theNum);
        });
        */

        //this works... the other one doesnt why?!?!
        var theNum = parseInt($(".test").html()) + 1;
        $(".test").html(theNum);
    }

    setInterval(change, 1000);

});

http://jsfiddle.net/DTyY7/


回答1:


You should use

$(this).html(theNum);

and not

this.html(theNum);

Because html() is a jQuery function and this (inside .each()) is a domElement and so you must wrap it into a jQuery object

Fiddle here: http://jsfiddle.net/nicolapeluchetti/DTyY7/2/




回答2:


this in your each() callback body should be changed to $(this):

$(".test").each(function(){
    var theNum = parseInt($(this).html())+1 || 0;
    $(this).html(theNum);
});

see this demo.




回答3:


it is applying the first instance of .test to all of them. You need to loop through all of the elements and apply a +1 separately.

$('.test').each(function(){
           $(this).html(parseInt($(this).html())+1)
        });



回答4:


you need to use $(this) instead this .I have updated the code http://jsfiddle.net/DTyY7/6/ .Hope it helps




回答5:


$(document).ready(function(){


function change(){

    $(".test").each(function(i, domElement){

        //var theNum = parseInt(this.html())+1;
        var num = parseInt($(".test").html());
        num++
        $(".test").html(num);
    });


    //this works... the other one doesnt why?!?!
      /* var theNum = parseInt($(".test").html())+1;
        $(".test").html(theNum);
*/}

setInterval(change,1000);

});

This is how you can fix it. Because you are in another scope the keword this doesn't work.




回答6:


$(document).ready(function() {
    function change() {
        $(".test").each(function(i,domeElement) {
            var theNum = parseInt($(this).html())+1;
            $(this).html(theNum);
        });
    }
    setInterval(change,1000);
});


来源:https://stackoverflow.com/questions/8490290/jquery-each-selector-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!