开发者

Attaching events to two items in JQuery

I would like to create a click event that will work when two different items are clicked. Is there a way to do this?

For example, normally what I'd do开发者_如何学运维 is this:

<a id="link1" onclick="doSomething()">link1</a>
<a id="link2" onclick="doSomething()">link2</a>

But what I would like to know is whether there is any event overloading of sorts, perhaps like:

<script>
$("#link1", "#link2").click(function () { 
 alert('doSomething');

 });
</script>

Thanks


The selector should look like this:

$("#link1, #link2")

Take a look at jQuery's multiple selector docs.


<script>
$("#link1, #link2").click(function () { 
 alert('doSomething');

 });
</script>


You can use a multiple selector by comma separating, like this:

$('#link1, #link2').click(function () { 
  alert('doSomething');
});

You can test it here.


But an easier approach is usually to give the links a common class, this way whether you have 2 links, no links or 400 links...there's no change to your code. To do that give them a class like this:

<a href="#" class="link">link1</a>
<a href="#" class="link">link2</a>

Then use a .class selector, like this:

$('.link').click(function () { 
  alert('doSomething');
});

You can test that version out here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜