开发者

jQuery generalizing dynamic selector input

I am in a situation where I need to use dynamic ID's of the format functionalDescription_IDNUMBER throughout my page and I need to target certain areas based on what the IDNUMBER was for the object that was clicked. However, I am not sure how to generalize the function so that I don't have to generate this same code for every开发者_运维知识库 unique ID (for instance, it could end in ABC, DEF, XYZ, asfSa1s3d6fZ, etc).

Example:

jQuery function that I would like to generalize (where XYZ is the dynamically generated ID Number in this case)...

$("#videoThumbnail_XYZ").click(function() {
    $("#thumbnailDescription_XYZ").fadeOut(300, function() {
        $("#videoPlayer_XYZ").fadeIn(100);
    });
});

For a given piece of HTML:

<div id="videoPlayer_XYZ" class="videoPlayer">
    <iframe title="Video Player" type="text/html" width="638" height="390" src="" frameborder="0"></iframe>
</div>
<div id="thumbnailDescription_XYZ" class="thumbnailDescription">
    <div id="videoThumbnail_XYZ" class="videoThumbnail left">
        <img src="images/videoThumbnail.png" />
    </div>
    <!-- more code in here -->
</div>


You can use the starts-with selector ^=

$("[id^='videoThumbnail']").click(function() {
    var id = $(this).attr("id").split("_")[1];
    $("#thumbnailDescription_" + id).fadeOut(300, function() {
        $("#videoPlayer_" + id).fadeIn(100);
    });
});

example: http://jsfiddle.net/m67Y7/1/


or using the same split() logic, attach the event to the videoThumbnail class

$(".videoThumbnail").click(function() {
    var id = $(this).attr("id").split("_")[1];
    $("#thumbnailDescription_" + id).fadeOut(300, function() {
        $("#videoPlayer_" + id).fadeIn(100);
    });
});

example: http://jsfiddle.net/m67Y7/


Another way you could do this is container based. Then all the selectors would be based on class with a live selector within <div data-videoid="XYZ"> instead of global unique id.

<div data-videoid="XYZ"> <!-- unique id is stored at parent level -->
    <div class="videoPlayer">
        <iframe title="Video Player" type="text/html" width="638" height="390" src="" frameborder="0"></iframe>
    </div>
    <div class="thumbnailDescription">
        <div class="videoThumbnail left">
            <img src="images/videoThumbnail.png" />
        </div>
    </div>
</div>


jQuery templates are a good way of templating markup with minor variations. Also, check out this jquery random string generator.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜