Javascript:ChangeOnClick动态更改为;“打开窗口”;
我想更改onclick的值,我尝试了这个,但没有成功。有什么帮助吗Javascript:ChangeOnClick动态更改为;“打开窗口”;,javascript,onclick,window.open,Javascript,Onclick,Window.open,我想更改onclick的值,我尝试了这个,但没有成功。有什么帮助吗 <a href='#' id='social' onClick="">click</a> document.getElementById("social").onclick = "open_new_window('https://twitter.com/share?url=https%3A%2F%2F"+url+"&via=iguestblogger&text="+titl
<a href='#' id='social' onClick="">click</a>
document.getElementById("social").onclick = "open_new_window('https://twitter.com/share?url=https%3A%2F%2F"+url+"&via=iguestblogger&text="+title+"');";
document.getElementById(“社交”).onclick=“打开新窗口”(“社交”)https://twitter.com/share?url=https%3A%2F%2F“+url+”&;via=iguestblogger&;text=“+title+”);”;
注意:
url
、title
和open\u new\u window()
已经定义好,可以正常工作。只需绑定事件,而不是更改onclick
属性的值
document.getElementById("social").onclick = function() {
open_new_window('https://twitter.com/share?url=https%3A%2F%2F'+url+'&via=iguestblogger&text='+title);
};
假设前面已经定义了url、标题和函数open\u new\u window,也请注意您的报价
<a href='#' id='social' >click</a>
<script>
document.getElementById("social").onclick = function()
open_new_window("https://twitter.com/share?url=https%3A%2F%2F"+url+"&via=iguestblogger&text="+encodeURI(title));
return false;
}
</script>
document.getElementById(“social”).onclick=function()
打开新窗口(“https://twitter.com/share?url=https%3A%2F%2F“+url+”&;via=iguestblogger&;text=“+encodeURI(title));
返回false;
}
在您的代码中,在赋值之前调用open\u new\u窗口
,其结果写入onclick
属性。因此,1)open\u new\u window
在onclick
更改之前(可能在页面加载期间)无条件执行,而不是在用户单击特定链接时执行;2) 单击链接将导致javascript错误,因为返回值可能不是函数和element.onclick=function(){alert('element已单击');}
@penartur感谢您的解释..我看到了我的错误。Hmmm-我不仅修复了报价,而且还返回false以停止点击href并对标题进行编码
<a href='#' id='social' >click</a>
<script>
document.getElementById("social").onclick = function()
open_new_window("https://twitter.com/share?url=https%3A%2F%2F"+url+"&via=iguestblogger&text="+encodeURI(title));
return false;
}
</script>
document.getElementById("social").onclick = open_new_window('https://twitter.com/share?url=https%3A%2F%2F"+url+"&via=iguestblogger&text="+title+"');