简体   繁体   English

从html触发javascript的正确方法

[英]Right way of triggering a javascript from html

What is the way for having a graphical component (more precisely a twitter.bootstrap icon) in an html website calling a java script. 在调用java脚本的html网站中使用图形组件(更确切地说是twitter.bootstrap图标)的方法是什么?

One could either make a button and putting the icon on it, but this does not look nice IMHO. 人们可以制作一个按钮并将图标放在上面,但这看起来不太好恕我直言。 Or one could use the href tag, 或者可以使用href标签,

<a href="#" name="ad_fav" onclick= CALLFUNCTION> <i
                        class="icon"></i></a>

But what is the cleanest way of achieving this? 但实现这一目标的最简洁方法是什么? It would also be nice if the icon could change after it was clicked. 如果图标在点击后可能会发生变化,那也很好。

How it for example the upvote button in stackoverflow implemented? 例如,如何实现stackoverflow中的upvote按钮?

Another way: 其他方式:

function myFunc () {
// code here
}

var element = document.getElementsByClassName("icon");
element[0].addEventListener("click", myFunc);

Just make the href of the <a> be 'javascript:', example: 只需将<a>的href设为'javascript:',例如:

<a href="javascript:alert('hello there! this works!')" name="ad_fav"> <i
                    class="icon"></i></a>

Replace alert(...) with your function call if you need 如果需要,用函数调用替换alert(...)

你没有用锚元素包装它:

<img src="[path to twitter.bootstrap icon]" onclick="yourJavaScriptFunction" />

Why wouldn't you use jquery on function? 你为什么不在函数上使用jquery?

$(document).on("click", "a.icon", function (e) {
    e.preventDefault();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM