I have a component with an ID that is composed of a first static part and a second dynamic value, like this:
<div id="smallPlacardone">
Where: smallPlacard
is static and one
is passed using a variable.
Later in my code I want to use the dynamic part of the ID, namely one
, but not the first static part smallPlacard
, like this:
var clicked = $(this).parent().attr("id");
$("#right"+clicked+"").show();
What's the best way of doing it?
If "smallPlacard" is static, then you can just remove it using the replace method:
var clicked = $(this).parent().attr("id").replace(/smallPlacard/, '');
$("#right" + clicked).show();
I recommend working with delimiter chars and split()
. It's easier to read and avoids the regex entirely:
<div id="smallPlacard_one">
and
var clicked = $(this).parent().attr("id").split("_")[1];
$("#right_" + clicked).show();
Alternatively something like this, which is more flexible because it does not rely on hidden conventions:
<div id="smallPlacard_one" data-show="#right_one">
and
var selector = $(this).data("show")
$(selector).show();
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.