0

我想访问以下标记中的 data-global-id 值,但由于范围界定,我不确定如何执行此操作。

例如:

<div data-global-id="168" class="remove-as-favorite">remove as favorite</div>

$('.remove-as-favorite').on('click',function(){
  var global_id=$(this).data('global-id');
  // this works
  alert('here i am in something: ' + global_id);
  // this doesn't work
  event_handler.remove_as_favorite(); 
});


// want to access the data-global-id value in here; how to get access to this?
event_handler={
remove_as_favorite: function(){
    // how to get access to this here; assuming this refers to event_handler 
    var global_id=$(this).data('global-id');
    alert("here i am global_id:" + global_id);
  }
}

谢谢

** 编辑 1 ** 在此处输入图像描述

4

3 回答 3

0

试试这个 bruv:使用 global_id http://jsfiddle.net/HK55Q/8/ http://jsfiddle.net/HK55Q/11/的工作演示

在代码中只是像这样在本地函数之外更改全局 id 的声明var global_id = "";

进一步的代码应该更好地解释,

好读:) 如何在 jQuery 中存储全局值(不一定是全局变量)?

希望它有帮助,让我知道我是否错过了什么

代码

var global_id = ""; //<=== See here the global_id variable is outside your click and now you can bind it and can use it again.

$('.remove-as-favorite').on('click',function(){
  global_id=$(this).data('global-id'); //<== Do not redeclare it using var global_id
  // this works
  alert('here i am in something: ' + global_id);
  // this doesn't work
  event_handler.remove_as_favorite(); 
});


// want to access the data-global-id value in here; how to get access to this?
event_handler={
remove_as_favorite: function(){
    // how to get access to this here; assuming this refers to event_handler 
    var global_id=$(this).data('global-id');
    alert("here i am global_id:" + global_id);
  }
}
于 2012-06-30T02:50:41.963 回答
0

你可以做几件事中的一件。我能看到的最简单的方法是将 global_id 作为参数传递给 remove_as_favorite 函数,它看起来像这样:

$('.remove-as-favorite').on('click',function(){
  var global_id=$(this).data('global-id');
  event_handler.remove_as_favorite(global_id); 
});

// want to access the data-global-id value in here; how to get access to this?
event_handler={
remove_as_favorite: function(global_id){
    alert("here i am global_id:" + global_id);

} }

另一种方法是使用“调用”或“应用”功能。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Call

$('.remove-as-favorite').on('click',function(){
  var global_id=$(this).data('global-id');
  event_handler.remove_as_favorite.call(this); 
});
于 2012-06-30T03:04:44.597 回答
0

一个更简单的例子是使用如下调用:​</p>

$(function(){
    $('.remove-as-favorite').on('click',function(){
        var global_id=$(this).data('global-id');
        alert('here i am in something: ' + global_id);
        event_handler.remove_as_favorite.call({global_id:global_id}); 
    });


    event_handler = {
        remove_as_favorite: function() {
            alert("here i am global_id:" + this.global_id);
        }
    }
});​

并且 call 是一个javascript函数,并且兼容所有支持javascript的浏览器;)

检查小提琴:http: //jsfiddle.net/nTq97/

于 2012-06-30T06:09:41.327 回答