开发者

Why can't .click be substituted with an onClick event?

开发者 https://www.devze.com 2023-01-07 01:05 出处:网络
How come this code will work perfectly fine: <script> $(\'.changeStuff\').click( function() { $(\'#number2\').val(12.00);

How come this code will work perfectly fine:

<script>
$('.changeStuff').click(
function() {
  $('#number2').val(12.00);
});
</script>

<body>
<h2 class="changeStuff">Lets change some stuff</h2>

<input name="number2" id="number2" value="11.00"> 
</body>

While this code, written to be used in 开发者_如何学编程an onClick event, wont work at all?

<script>
function change_stuff(b) {
  $('#number2').val(b);
}
</script>

<body>
<h2 onclick="change_stuff('12.00')">Lets change some stuff</h2>

<input name="number2" id="number2" value="11.00"> 
</body>


I think the h2 element doesn't have an onclick event in all browsers. That's why the second way might work but now in all browsers. When you run a jQuery selector on the h2 element the jQuery library "wrapped" the element giving it all of the jQuery events and function.

And then because the jQuery object has a click event and jQuery works an all browsers that way worked for you.

So thanks again to jQuery! for making our lives easier.

0

精彩评论

暂无评论...
验证码 换一张
取 消