Javascript 访问输入标记的ID attibute时获得一个奇怪的数字
我想为输入标记获取id属性的值Javascript 访问输入标记的ID attibute时获得一个奇怪的数字,javascript,jquery,Javascript,Jquery,我想为输入标记获取id属性的值 <input type="text" id="heading1" class="alert-heading" value="aaa" /> 但是,当我拿到身份证时,我会得到一个奇怪的号码,尽管我希望得到一个“头像1” 这就是我现在正在编写的代码 var alertHeading = $(".alert-heading"); alertHeading.on('blur', function(){ var key = alertMode.va
<input type="text" id="heading1" class="alert-heading" value="aaa" />
但是,当我拿到身份证时,我会得到一个奇怪的号码,尽管我希望得到一个“头像1”
这就是我现在正在编写的代码
var alertHeading = $(".alert-heading");
alertHeading.on('blur', function(){
var key = alertMode.val();
chrome.runtime.getBackgroundPage(function(backgroundPage) {
var background = backgroundPage.background;
var alertObject = background.getStorage(key);
//(EDITED)Oh I think $(this)here no longer points to the input element!!
var headingId = $(this).attr("id");
console.log(headingId); // outputs 2943. I'm expecting "heading1".
});
})
请帮我解决这个问题。
提前谢谢 您需要将此
保存在闭包变量中:
alertHeading.on('blur', function(){
var key = alertMode.val();
var that = this;
chrome.runtime.getBackgroundPage(function(backgroundPage) {
var background = backgroundPage.background;
var alertObject = background.getStorage(key);
var headingId = that.id;
console.log(headingId);
});
});
您需要将此
保存在闭包变量中:
alertHeading.on('blur', function(){
var key = alertMode.val();
var that = this;
chrome.runtime.getBackgroundPage(function(backgroundPage) {
var background = backgroundPage.background;
var alertObject = background.getStorage(key);
var headingId = that.id;
console.log(headingId);
});
});
用ECMAScript术语解释这一点,每次创建新控件时。每个执行上下文都有自己的
thisBinding
,因此您需要存储对外部上下文的this
引用的引用,以便可以通过访问它
我正在使用el.id
来访问el
引用的DOM元素的id
属性。只要有可能,最好使用DOM而不是HTMLattr
ibutes
词法范围技巧是最常见的方法,但有几种方法可以解决这个问题 在ES5中,也可以将函数对象的
引用:
alertHeading.on('blur', function(){
chrome.runtime.getBackgroundPage(function(backgroundPage) {
// [...]
var headingId = this.id; //2. Now it has the same this as outer scope
}.bind(this)); //1. The onblur's `this` is bound to the bgpage callback
});
用ECMAScript术语解释这一点,每次创建新控件时。每个执行上下文都有自己的thisBinding
,因此您需要存储对外部上下文的this
引用的引用,以便可以通过访问它
我正在使用el.id
来访问el
引用的DOM元素的id
属性。只要有可能,最好使用DOM而不是HTMLattr
ibutes
词法范围技巧是最常见的方法,但有几种方法可以解决这个问题
在ES5中,也可以将函数对象的引用:
alertHeading.on('blur', function(){
chrome.runtime.getBackgroundPage(function(backgroundPage) {
// [...]
var headingId = this.id; //2. Now it has the same this as outer scope
}.bind(this)); //1. The onblur's `this` is bound to the bgpage callback
});
将$(此)
替换为$(“.alert heading”)
,因为$(此)
可能不是您所认为的那样顺便说一下$alertHeading
是一个很好的变量名称,因为它注意到它是一个jquery对象。它对我来说工作正常,您检查过了吗?因为当我尝试它的工作很好,给我你想要的输出。将您的代码包装在$(文档)中。ready()
用$(“.alert heading”)
替换$(this)
,因为$(this)
可能不是您所认为的那样。$alertHeading
是一个很好的变量名称,因为它注意到它是一个jquery对象。它对我来说很好,您检查过了吗?因为当我尝试它的工作很好,给我你想要的输出。将代码包装在$(document.ready()
中,而不是$(that.attr(“id”)
使用that.id
而不是$(that).attr(“id”)
使用that.id代码>+1用于指出使用domeElement.id
属性的良好做法。+1用于指出使用domeElement.id
属性的良好做法。