简体   繁体   中英

Pass a variable inside a function Jquery

I have written this code:

var idImg = 'something';
$('#'+idImg).clickToggle(addMarker, destroyMarker);

Where clickToggle() is:

    $.fn.clickToggle = function(func1, func2) {

        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function() {
            var data = $(this).data();
            var tc = data.toggleclicked;
            //$.proxy(funcs[tc], this)();
            funcs[tc].call(this);
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };

And addMarker() is a function which needs to get the variable idImg.

How can I pass the global variable idImg inside the addMarker function?

Thanks

EDITED

 $(document).ready(function(){
     $('img').hover(function() { 
       var idImg = $(this).attr('id');      
       $('#'+idImg).clickToggle(addMarker, destroyMarker);});
  });




 $.fn.clickToggle = function(func1, func2) {

    var funcs = [func1, func2];
    this.data('toggleclicked', 0);
    this.click(function() {
        var data = $(this).data();
        var tc = data.toggleclicked;
        $.proxy(funcs[tc], this)();
        data.toggleclicked = (tc + 1) % 2;
    });
    return this;
 };

var addMarker = function(){ alert(idImg)}  <-- I WANT THIS

 var destroyMarker = function(){
        DO SOMETHING ELSE
 };

You can use an anonymous function

$('#'+idImg).clickToggle(function(){
    addMarker(idImg)
}, destroyMarker);

Demo: Fiddle

But in this case since that is the id of the button, this inside addMarker refers to the button so you could also use this.id to refer to something .

Demo: Fiddle

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