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')});