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