在图像单击上运行 Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19114183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run Javascript on Image Click
提问by Michael Alexander-Thorn
I have the following graphical button on my site:
我的网站上有以下图形按钮:
<a href="#" class="addto_cart_btn">
<span id="btn_text">Click here to add to cart now</span>
</a>
I want to run a specific javascript script when clicked (current value #) to run some javascript - the javascript code essentially generates a popup iFrame with additional content in it.
我想在单击时运行特定的 javascript 脚本(当前值 #)来运行一些 javascript - javascript 代码本质上会生成一个带有附加内容的弹出式 iFrame。
What is the best approach for achieving this?
实现这一目标的最佳方法是什么?
回答by Gurminder Singh
try this
试试这个
<script type="text/javascript">
window.onload = function() {
document.getElementById("btn_text").onclick = function() {
// Do your stuff here
};
};
</script>
Or if you can use JQuery
或者,如果您可以使用 JQuery
<script type="text/javascript">
$(document).ready(function() {
$("#btn_text").click(function(){
// Do your stuff here
});
});
</script>
回答by Alex
One approach is to add an onclick attribute
一种方法是添加一个 onclick 属性
<a href="#" class="addto_cart_btn" onclick="someFunction()">
<span id="btn_text">Click here to add to cart now</span>
</a>
And then the javascript:
然后是javascript:
function someFunction(){
//do stuff
}
回答by Chokchai
for plain javascript
对于普通的 javascript
window.onload = function(){
document.getElementById('btn_text').onclick = function(){
// do stuff;
}
}
for jQuery
对于 jQuery
jQuery(function($){
$('#btn_text').on('click', function(){
// do stuff
})
})
回答by krish
You should use OnClick attribute
您应该使用 OnClick 属性
<a href="#" class="addto_cart_btn" onclick="yourFunction();">
<span id="btn_text">Click here to add to cart now</span>
</a>