如何将点击绑定到没有框架的锚点(javascript) [英] How do I bind a click to an anchor without a framework (javascript)
问题描述
< a href =doc.htmlonclick = myFunc(); return false>点击这里< / a>
,这会导致我的JavaScript对于启用JS的浏览器执行,并且链接对于那些没有javascript?
现在,我如何以非内联的方式做同样的事情?
如果您只需分配一个单击
事件,则可以分配 onclick
:
如果您有一个ID:
myAnchor = document.getElementById (锚);
myAnchor.onclick = function(){myFunc();返回假
您还可以浏览所有锚点:
anchors = document.getElementsByTagName(a);
for(var i = 0; i< anchors.length; i ++){
anchors [i] .onclick = .....
}
还有一个 document.getElementsByClassName
来模拟jQuery的类选择器,但所有浏览器都不支持。
如果可能需要在一个元素上分配多个事件,请与<$由@Jordan和@David Dorward显示的c $ c> addEventListener
I know this is easily done in jQuery or any other framework, but that's not really the point. How do I go about 'properly' binding a click event in pure javascript? I know how to do it inline (I know this is terrible)
<a href="doc.html" onclick="myFunc(); return false">click here</a>
and this causes my javascript to execute for a JS enabled browser, and the link to behave normally for those without javascript?
Now, how do I do the same thing in a non-inline manner?
If you need to assign only one click
event, you can assign onclick
:
If you have an ID:
myAnchor = document.getElementById("Anchor");
myAnchor.onclick = function() { myFunc(); return false; }
you can also walk through all anchors:
anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].onclick = .....
}
There's also a document.getElementsByClassName
to simulate jQuery's class selector but it is not supported by all browsers.
If it could be that you need to assign multiple events on one element, go with addEventListener
shown by @Jordan and @David Dorward.
这篇关于如何将点击绑定到没有框架的锚点(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!