简体   繁体   中英

Jquery Select Dynamic ID

I'm trying to toggle the visibility of this. You'll notice there's a primary key number at the end of the id:

<div id="campaign-details-container-12">

And this is how I've tried to select it:

$(document).on("click",".show-details",function () {
    $(this).blur();
    var id = $(this).data("id");
    var selector = "#campaign-details-container-"+id;
    alert(selector);

    $(selector).toggle();
    return false;
});

How can I get this to work? I could put a data-id="12" tag in the div instead and use a class, but how would I select by that?

Just select it using the attribute starts with syntax:

$("[id^=campaign-details-container]");

No need to go do unnecessary things with classes and id variables...

See http://www.w3schools.com/cssref/sel_attr_begin.asp

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