开发者

Triggering a jQuery function when the page loads and when a link is clicked?

开发者 https://www.devze.com 2023-03-30 14:46 出处:网络
I\'m using this function: $(document).ready(function() { $(\'.gdthumbtext\') .contents() .filter( function(){

I'm using this function:

$(document).ready(function() {

$('.gdthumbtext')
.contents()
.filter( function(){
    return this.nodeType == 3;
}).each(function(){
    this.nodeValue= this.nodeValue.replace(/\+/g,'');
});

});

To remove plus signs before numbers inside the .gdthumbtext div. Now the problem is that the number will change with ajax each time you click a link with the class .gdt-starrating.

I guess I have to ca开发者_如何学Cll (or recall) that function again when the link is clicked.

Maybe I need something like this: call the function when page loads or when the link with class .gdt-starrating is clicked.

Any suggestions of how to do that?


You can move the code into it's own function, call that function onload then continue to call the function each time the link is clicked. Like this:

$(document).ready(function() {
    // Call cleanup onload
    stripPlusSigns();

    $('a.gdt-starrating').click(function() {
        // Do stuff here...
        // ...

        // Strip plus signs again
        stripPlusSigns();
    });
});

function stripPlusSigns()
{
    $('.gdthumbtext')
        .contents()
        .filter( function(){
             return this.nodeType == 3;
        }).each(function(){
             this.nodeValue= this.nodeValue.replace(/\+/g,'');
        });

    return true;
}


You have the right idea.

You should be running it on ajax Sucess after your ajax content is loaded. I've included both click and ajax.

$(document).ready(function() {

    // run on page load
    removeSigns();

    // you could run on ajax load
    $('.gdt-starrating').bind('click', function() {
        removeSigns();
    });

    // you should be running it on Ajax success callback
    $.ajax({ 
            // your normal ajax stuff...

        success : function() {
            removeSigns();
        } 
    });

});


function removeSigns() {
    $('.gdthumbtext')
    .contents()
    .filter( function(){
        return this.nodeType == 3;
    }).each(function(){
        this.nodeValue= this.nodeValue.replace(/\+/g,'');
    }

); }

0

精彩评论

暂无评论...
验证码 换一张
取 消