Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript添加onclick失败_Javascript_Html - Fatal编程技术网

Javascript添加onclick失败

Javascript添加onclick失败,javascript,html,Javascript,Html,我的剧本: function $(attr){ if(attr.charAt(0) == "#"){ return document.getElementById(attr.substr(1)); }else{ if(attr.charAt(0) == "."){ return document.getElementsByClassName(attr.substr(1)); }else{

我的剧本:

function $(attr){
    if(attr.charAt(0) == "#"){
        return document.getElementById(attr.substr(1));
    }else{
        if(attr.charAt(0) == "."){
            return document.getElementsByClassName(attr.substr(1));
        }else{
            return document.getElementsByTagName(attr);
        }
    }
}

Object.prototype.onclick = function(script){
    this.onclick = script;
}

$("#hi").onclick(function(){alert("hi");});
在html中,它只是一个id为hi的标签

当我点击按钮时,什么也没发生。
我该怎么办?

扩展
对象是一种不好的做法,我不推荐这样做。此外,在现代浏览器中,您想做的事情相当简单,您可以使用并添加以下事件:

$("#hi").onclick=function(){alert("hi");}

你可以就这样离开

<script type="text/javascript"> 
function $(attr){
    if(attr.charAt(0) == "#"){
        return document.getElementById(attr.substr(1));
    }else{
        if(attr.charAt(0) == "."){
            return document.getElementsByClassName(attr.substr(1));
        }else{
            return document.getElementsByTagName(attr);
        }
    }
}

$("#hi").onclick = function(){alert("hi");};
</script>

函数$(attr){
如果(属性字符(0)=“#”){
返回document.getElementById(attr.substr(1));
}否则{
如果(属性字符(0)=“0”){
return document.getElementsByClassName(attr.substr(1));
}否则{
返回文档.getElementsByTagName(attr);
}
}
}
$(“#hi”).onclick=function(){alert(“hi”);};
这是一个jsfiddle

我的朋友在将页面加载到浏览器中后,使用Inspect元素检查ID

我猜您正在使用ASP.NET和母版页,并且您的#hi元素位于contentPlaceHolder中。如果我的猜测是正确的,那么您的元素#hi必须已更改为类似ContentPlaceholder 1#hi的内容。因此,根据这一点,请更改您的脚本

$('#ContentPlaceHolder1_hi').click(function(){alert('hi')});

我希望这会有所帮助。

如果您不需要对非常旧的浏览器的支持,我只需要使用
querySelectorAll
,请参见此处
getElementsByClassName
在旧IE中也不太受支持。
document.getElementById(…).onclick不是函数。
解决方案?
$('#ContentPlaceHolder1_hi').click(function(){alert('hi')});