我正在开发自己的 JavaScript 库。该库有一个 getAttr()
函数,其操作如下:tex(selector).getAttr(name);
这是该库的代码:
(function(){
var tex = function(s){
return new tex.fn.init(s);
};
tex.fn = tex.prototype ={
init : function(s){
if(!s){
return this;
}
else{
this.length = 1;
if (typeof s === "object"){
this[0] = s;
}
else if(typeof s === "string"){
var obj;
obj = document.querySelector(s);
this[0] = obj;
}
return this;
}
}
}
tex.fn.init.prototype = tex.fn;
tex.fn.init.prototype = {
attr : function(name, value){
/*if(name && !value){
return this[0].getAttribute(name);
}else if(name && value){
this[0].setAttribute(name,value);
};*/
this[0].setAttribute(name,value);
},
getAttr : function(name){
return this[0].getAttribute(name);
},
removeAttr : function(name){
this[0].removeAttribute(name);
},
print : function(txt){
this[0].innerHTML = txt;
}
};
window.TechX = tex;
})();
这是正文部分的代码:
<nav>
<ul>
<li><a id="MainDropper">Pick your method:</a>
<ul>
<li><a>book</a>
<ul>
<li><a data-val="Book" href="javascript:setType(this)">Book</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
这是我在 head 部分的代码:
function setType(obj){
tex("#MainDropper").print(tex(obj).getAttr("data-val"));
}
因此,当我单击图书链接时,邮件投递器应该显示文本“图书”。但相反,我在库中收到一条错误消息:“[全局对象] 没有方法 getAttrribute
。”有谁知道我该如何解决这个问题?
非常感谢。
最佳答案
功劳真的应该归功于 Bergi,但为了提供答案,这里是。
当你使用像这样的监听器时:
<a onclick="code" ... >
然后 onclick 属性的内容有效地包装在一个函数中,该函数以 this 元素调用,例如:
function listener(){code}
listener.call(element);
但是,当使用 href 属性和 javascript 伪协议(protocol)(又名“javascript: URL scheme”)时,代码将作为全局代码执行,因此或多或少只是:
code;
HTML5 说要表现得好像插入了一个新的脚本元素,代码作为内容。因此在监听器函数(执行上下文)中,this 将引用全局(窗口)对象。
请注意,浏览器的行为在这里可能有所不同(例如,在 javascript URL 中声明的变量),因为在 HTML5 之前没有关于如何处理此类代码的规范,它实际上只是试图指定浏览器已经执行的一个版本。以前,它作为 DOM 0 的一部分保留*,这是浏览器在 W3C 规范之前所做的所有 DOM 内容,这些内容未成为新规范的一部分。
* DOM 0 是“……Netscape Navigator 3.0 版和 Microsoft Internet Explorer 3.0 版提供的 HTML 文档功能的混合(未正式指定)。” W3C DOM Level 1 01-Oct-1998 .
关于attributes - Javascript 库 .getAttr() 函数不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19382946/