[英]How to get the attr with jQuery?
<div class="item">
<p><img src="images/photos_sample1.jpg"
border="0" rel="images/google_map.jpg"></p>
<p>Dining Area</p>
</div>
<div class="item">
<p><img src="images/photos_sample2.jpg"
border="0" rel="images/sample_photo.jpg"></p>
<p>Pool Area</p>
</div>
I have the above HTML code and I want to get the rel
attribute's value when I click the image. 我有上面的HTML代码,我想在单击图像时获取rel
属性的值。 I wrote this jQuery script, but it doesn't seem to work: 我写了这个jQuery脚本,但它似乎不起作用:
$('div.item').click(function() {
var getvalue = $('this > p > img').attr('rel');
alert(getvalue);
});
Replace this: 替换这个:
var getvalue = $('this > p > img').attr('rel');
With this: 有了这个:
var getvalue = $(this).find('p > img').attr('rel');
As it is right now you are doing a global search for elements with the literal tag name this
因为它是现在你在做一个全局搜索与文字标签名称元素this
An equivalent code would also be: 等效代码也将是:
var getvalue = $('p > img', this).attr('rel');
Although by the looks of it the items are image/caption combinations and you wouldn't really expect other images, in which case it is better to just do: 虽然从它的外观来看,这些项目是图像/标题组合,你不会真正期待其他图像,在这种情况下,最好只做:
var getvalue = $(this).find('img').attr('rel');
Or maybe give it a descriptive class and replace img
with img.someclassname
- this would make it so that if you edit your HTML later on your Javascript doesn't break because of your specific selector. 或者也许给它一个描述性的类并用img.someclassname
替换img
- 这将使得如果你以后编辑HTML你的Javascript不会因为你的特定选择器而中断。
Furthermore, you could just bind the click event to the images themselves: 此外,您可以将click事件绑定到图像本身:
$('div.item img').click(function() {
var getvalue = $(this).attr('rel');
});
$('div.item').click(function() {
var getvalue = $(this).find('> p > img').attr('rel');
alert(getvalue);
});
You can't use 'this' like this. 你不能像这样使用'this'。
Try: 尝试:
$('div.item').click(function() {
var getvalue = $('p > img', this).attr('rel');
alert(getvalue);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.