简体   繁体   中英

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()"?

What would be the best approach?

Thanks

They are functionally equivalent. Which is best? Neither. Don't mix markup and 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() . Note that you could also write onclick="foobarbaz:fnq()" , and it would do the same thing; there's absolutely nothing special about the 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.)

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.

I believe that putting javascript inline has been depreciated by W3C.

Only use the inline javascript when you are trying use two different scripting languages with your event handlers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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