简体   繁体   English

调用javascript函数onclick =“ fn1()”和onclick =“ javascript:fn1()”时有什么区别

[英]Is there any difference when calling a javascript function onclick=“fn1()” and onclick=“javascript:fn1()”

What is the difference between calling a function directly onclick="fn1()" and onclick="javascript:fnq()"? 直接在onclick =“ fn1()”和onclick =“ javascript:fnq()”上调用函数有什么区别?

What would be the best approach? 最好的方法是什么?

Thanks 谢谢

They are functionally equivalent. 它们在功能上是等效的。 Which is best? 哪个最好? Neither. 都不是。 Don't mix markup and JavaScript. 不要混合使用标记和JavaScript。 Instead, bind a function to your element: 而是将函数绑定到您的元素:

<div id="element"></div>

Now there are multiple ways to do this: 现在有多种方法可以做到这一点:

// Find element
var el = document.getElementById('element');

// Option 1:
el.onclick = function() {
    fn1();
};

// Or by reference:
el.onclick = fn1;

// Option 2:
if (el.addEventListener) {
    el.addEventListener('click', fn1, false);
} else {
    el.attachEvent('click', fn1);
}

The difference is that onclick="fn1()" means what you think it does ("run the function fn1() "), while onclick="javascript:fnq()" is using javascript: as a useless label for the statement fnq() . 区别在于onclick="fn1()"表示您认为的功能(“运行函数fn1() “),而onclick="javascript:fnq()"使用javascript:作为fnq()语句的无用标签 fnq() Note that you could also write onclick="foobarbaz:fnq()" , and it would do the same thing; 请注意,您还可以编写onclick="foobarbaz:fnq()" ,它会做同样的事情; there's absolutely nothing special about the javascript . javascript绝对没有什么特别的。 (You may be thinking of the use of javascript: as a URL protocol in <a href="javascript:fnq()"> , where the javascript: serves the same general purpose as http: would: it indicates the type of URL.) (您可能会考虑使用javascript:作为<a href="javascript:fnq()">的URL协议,其中javascript:http:将具有相同的通用用途:它将指示URL的类型。 )

Of these, onclick="fn1()" is the better practice, though it's generally better to attach the click-handler from JavaScript, rather than putting it in the HTML to begin with. 其中, onclick="fn1()"是更好的做法,尽管通常最好从JavaScript附加点击处理程序,而不是先将其放入HTML。

I believe that putting javascript inline has been depreciated by W3C. 我相信W3C已将javascript内联。

Only use the inline javascript when you are trying use two different scripting languages with your event handlers. 仅当尝试在事件处理程序中使用两种不同的脚本语言时,才使用内联javascript。

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

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