开发者

use variable part of ID with js

开发者 https://www.devze.com 2023-04-01 09:46 出处:网络
I have a list of 8 divs:开发者_StackOverflow #video1, #video2, ... with each the same javascript actions to run when clicked, but with other id\'s (for #video1: show #image1, #preview1, ...).

I have a list of 8 divs:开发者_StackOverflow #video1, #video2, ... with each the same javascript actions to run when clicked, but with other id's (for #video1: show #image1, #preview1, ...).

Instead of writing 8 times the same code but with other id's, can I do this more efficient? Is it possible to take the sixth caracter (the number) from each #videoX as a variable when clicked, and use this in the code?


Inside your event handler, you can extract the number, e.g. with a regular expression [MDN]:

var id = element.id.match(/\d+$/)[0];

and then use it to create the IDs of the other elements:

var image_id = "image" + id,
    preview_id = "preview" + id;

Another option would be to assign data- attributes to the elements and use them to store the numerical part of the ID.


Use a class name instead. This way it's independent of the IDs completely.

<div class="videoClick" id="...">...</div>

JS:

$('.videoClick').click(function() {
...
})


yes you can:

$("div[id*='video']").click(function() {
   var numid = $(this).attr("id").replace("video", "");
   alert(numid);
   //...use your numid value
});

Check attribute contains selector.


Try this

var ids = [#video1, #video2, #video3, #video4, #video5, #video6, #video7, #video8];

$(ids.join(",")).click(function(){
    var imageId = this.id.replace("video", "image");
    var previewId = this.id.replace("video", "preview");
    $("#"+imageId).show();
    $("#"+previewId).show();

});
0

精彩评论

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