简体   繁体   中英

jQuery select all items with id attribute and having a given class

What i'm trying to do is to select all items where ID attribute starts with a given string but also having a class. For example i have this:

<div id="test-id-1" class="test"></div>
<div id="test-id-2" class="test selected"></div>
<div id="test-id-3" class="test"></div>

so i'm trying using something like this:

jQuery('div[id^="test-id-"].selected').trigger('click');

but it doesn't work. It should return only the second item in my example. How can i do this?

Many thanks in advance, :)

A simpler way to trigger a click event is:

$('div[id^="test-id-"].selected').click();

Also remember to ensure that the element is actually loaded when you execute this code.

Here is an example: http://jsfiddle.net/qy5Yc/

It seems you haven't been wrapping your code in document.ready which means if code is run before the html exists it will not bind handlers to non existent elements. Using the ready event wrapper assures that elements exist when code fires

Reference:

http://api.jquery.com/ready/

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