如何使用jQuery获取attr? [英] How to get the attr with jQuery?

查看:105
本文介绍了如何使用jQuery获取attr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<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>

我有上面的HTML代码,我想获得 rel 属性的值。我写了这个jQuery脚本,但它似乎不起作用:

I have the above HTML code and I want to get the rel attribute's value when I click the image. I wrote this jQuery script, but it doesn't seem to work:

$('div.item').click(function() {
  var getvalue = $('this > p > img').attr('rel');
  alert(getvalue);
});


推荐答案

替换为:

var getvalue = $('this > p > img').attr('rel');

这个:

var getvalue = $(this).find('p > img').attr('rel');

现在你正在全局搜索文字标签名称<$ c的元素$ c>此

As it is right now you are doing a global search for elements with the literal tag name this

等效代码也是:

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');

或者给它一个描述性的类并替换 img 使用 img.someclassname - 如果你以后编辑HTML,你的Javascript不会因为你的特定选择器而中断。

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.

此外,您可以将click事件绑定到图像本身:

Furthermore, you could just bind the click event to the images themselves:

$('div.item img').click(function() {
    var getvalue = $(this).attr('rel');
});

这篇关于如何使用jQuery获取attr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆