如何将属性 ID 的值存储到变量中?Jquery Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5759560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store the value of attribute ID to a variable? Jquery Javascript
提问by TaylorMac
Ok, so this is probably obvious.
好的,所以这可能是显而易见的。
I need to get the ID of a clicked div:
我需要获取点击的 div 的 ID:
$("div.editable").click(function(e) {
var editid = $(this).attr("id");
});
And the use that ID in a function w/parameters:
并在带有参数的函数中使用该 ID:
ajaxStyle(value, 2, editid)
But it doesn't work when I write it like this. It either returns "undefined" or just doesn't work.
但是当我这样写时它不起作用。它要么返回“未定义”,要么就是不工作。
回答by Johnner
var editid;
$("div.editable").click(function(e) {
editid = $(this).attr("id");
});
It's all about function scope.
这都是关于函数作用域的。
回答by Oded
You are declaring your editid
variable within a function, so it is only visible within it and not defined outside of it.
您editid
在函数中声明变量,因此它仅在函数内部可见,而不能在函数外部定义。
This will work (though will pollute the global namespace):
这将起作用(尽管会污染全局命名空间):
var editid;
$("div.editable").click(function(e) {
editid = $(this).attr("id");
});