Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用jQuery获取属性?_Javascript_Jquery_Attributes - Fatal编程技术网

Javascript 如何使用jQuery获取属性?

Javascript 如何使用jQuery获取属性?,javascript,jquery,attributes,Javascript,Jquery,Attributes,替换此项: $('div.item').click(function() { var getvalue = $('this > p > img').attr('rel'); alert(getvalue); }); 为此: var getvalue = $('this > p > img').attr('rel'); 现在,您正在使用文本标记名this 等效的代码也将是: var getvalue = $(this).find('p > img').at

替换此项:

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

var getvalue = $('this > p > img').attr('rel');
现在,您正在使用文本标记名
this

等效的代码也将是:

var getvalue = $(this).find('p > img').attr('rel');
虽然从外观上看,这些项目是图像/标题组合,您不会真的期望看到其他图像,但在这种情况下,最好只执行以下操作:

var getvalue = $('p > img', this).attr('rel');
或者给它一个描述性类,并用
img.someclassname
替换
img
——这样,如果以后在Javascript上编辑HTML,它就不会因为特定的选择器而中断

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

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

你不能这样用“这个”

尝试:

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