我希望能够访问以下标记中的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);
}
}
THX
**编辑1 **
答案 0 :(得分:0)
试试这个bruv:使用global_id工作演示 http://jsfiddle.net/HK55Q/8/ 或 http://jsfiddle.net/HK55Q/11/
在代码中仅仅更改本地函数之外的全局id声明,如var global_id = "";
此外,代码应该更好地解释,
好读:) How to store a global value (not necessarily a global variable) in 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);
}
}
答案 1 :(得分: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);
});
答案 2 :(得分:0)
一个更简单的例子是使用如下调用:
$(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);
}
}
});
并且调用是一个javascript函数,并且兼容所有支持javascript ofcourse的浏览器;)