最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Tie a button to a javascript function - Stack Overflow

programmeradmin4浏览0评论

I have a button in html:

<button id="MyButton" onclick="return DoSomething()">Click Me</button>

Is it better to put the "onclick" property in the html or use javascript/DOM to attach a callback to the button click?

I have a button in html:

<button id="MyButton" onclick="return DoSomething()">Click Me</button>

Is it better to put the "onclick" property in the html or use javascript/DOM to attach a callback to the button click?

Share Improve this question asked Feb 16, 2010 at 18:49 Robert DemlRobert Deml 12.5k21 gold badges69 silver badges92 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 9

It's considered better to attach it via JavaScript. This falls under the category of "Unobtrusive JavaScript". (more specifically here the separation of behavior from the layout)

document.getElementById('YourID').onclick = nameOfFunctionToBeCalled;

Favoring separation of presentation and logic, I'd suggest you bind events to it via the Javascript:

document.getElementById("MyButton").onclick = function(){
  alert("Button Clicked");
}

Keep your Javascript and CSS out of your HTML, and you'll be a happier developer. This method allows your programmers to write the Javascript, and your Designers to build the structure and styling. You don't want to put programming into the hands of a designer (which is what happens with inline javascript).

It's a better practice to do this purely from within Javascript, and keep your markup clean. If you're using a separate .js file, this also saves you from having to worry about issues with inline JS code inside HTML.

Using raw DOM it's pretty simple:

document.getElementById( "MyButton" ).onclick = DoSomething;

How about jQuery click()

$('#MyButton').click(DoSomething);

I use the ondomready event to assign all my events, normally squirreled away in a separate script. All my logic is in one place and my markup looks a lot tidier too. I hold the view that markup is merely there to describe the initial structure of the page. Code lives in a code file, and styles belong in a css file.

发布评论

评论列表(0)

  1. 暂无评论