jQuery 获取选择器值帮助
我有一个 WP 博客,其中有一些通过 PHP 循环生成的 DIV。我希望能够在有人单击 DIV 时显示有关该 DIV 的更多信息。
代码如下所示:(
<div class="story item-1">
<div class="story item-2">
<div class="story item-3">
<div class="story item-4">
等等。可以是任意数量的。)
单击上面的其中一项应该会出现以下内容之一:
<div class="data preview-1">
<div class="data preview-2">
<div class="data preview-3">
<div class="data preview-4">
我正在执行以下操作:
$('.story').click( function() {
var getNum = jQuery(this).attr('class');
alert('hi ' + getNum);
});
但是如何提取“数字”值(1 、2、3、4 等)我刚刚单击到变量中的项目?如果我可以将其放入诸如“num”之类的变量中,我就可以轻松地使用 jQuery .hide 和 .show 来执行操作。到目前为止我所拥有的得到了整个班级的价值。只需要二等的号码即可。
我将不胜感激任何帮助!谢谢!
I have a WP Blog with a few DIVs generated through PHP loops. I would like to be able to show additional about a DIV when someone clicks on it.
The code looks like this:
<div class="story item-1">
<div class="story item-2">
<div class="story item-3">
<div class="story item-4">
(etc. Could be any number of these.)
Clicking on one of the items above should make one of the following appear:
<div class="data preview-1">
<div class="data preview-2">
<div class="data preview-3">
<div class="data preview-4">
I'm doing the following:
$('.story').click( function() {
var getNum = jQuery(this).attr('class');
alert('hi ' + getNum);
});
But how do extract the "number" value (1,2,3,4,etc.) of the item I just clicked into a variable? If I can get that into a variable such as "num" I can then easily use jQuery .hide and .show to perform actions. What I have so far gets the entire class value. Just need the number from the second class.
I'd appreciate any help! Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会
.split()
在连字符上,和.pop()
结果数组中的最后一项(数字)。然后.show()
适当的预览。I'd
.split()
on the hyphen, and.pop()
the last item (the number) off the resulting array. Then.show()
the appropriate preview.当然,您可以使用字符串操作来提取id,但我提出了一个更好的解决方案:
在
DOMReady
上,循环遍历所有div,并为元素分配一个索引使用jQuery的轻量级数据存储机制,.data()
:免责声明:未经测试
然后您可以在单击中将其拉出:
这只是一个示例,您最终可能需要额外的元数据,并且您可以将任何您想要的内容绑定到元素,并在以后使用它们。
Of course you could use string manipulation to pull out the id, but I propose a better solution:
On
DOMReady
, loop through all the div's, and assign an index to the elements using jQuery's lightweight data storage mechanism,.data()
:Disclaimer: untested
Then you can pull it out in your click:
That's just an example, you may end up needed extra metadata, and you can bind whatever you want to the elements, and use them later.