jQuery 概括动态选择器输入
我遇到的情况是,我需要在整个页面中使用 functionDescription_IDNUMBER
格式的动态 ID,并且我需要根据对象的 IDNUMBER
来定位某些区域被点击。但是,我不确定如何概括该函数,这样我就不必为每个唯一 ID 生成相同的代码(例如,它可能以 ABC、DEF、XYZ、asfSa1s3d6fZ 等结尾)。
示例:
我想要概括的 jQuery 函数(在本例中,XYZ 是动态生成的 ID 号)...
$("#videoThumbnail_XYZ").click(function() {
$("#thumbnailDescription_XYZ").fadeOut(300, function() {
$("#videoPlayer_XYZ").fadeIn(100);
});
});
对于给定的 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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 starts-with 选择器
^=
示例: http://jsfiddle.net/m67Y7/1/
或使用相同的
split()
逻辑,将事件附加到videoThumbnail
类示例:http:// /jsfiddle.net/m67Y7/
You can use the starts-with selector
^=
example: http://jsfiddle.net/m67Y7/1/
or using the same
split()
logic, attach the event to thevideoThumbnail
classexample: http://jsfiddle.net/m67Y7/
另一种方法是基于容器。然后,所有选择器都将基于
中带有实时选择器的类,而不是全局唯一 id。
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.jQuery 模板 是一种带有细微变化的模板化标记的好方法。另外,请查看这个 jquery random 字符串生成器。
jQuery templates are a good way of templating markup with minor variations. Also, check out this jquery random string generator.