使用 jQuery 获取标题属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10490162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:25:25  来源:igfitidea点击:

Get title attribute with jQuery

jqueryjquery-mobile

提问by user1238565

I have a jQuery Mobile accordion menu set up like:

我有一个 jQuery Mobile 手风琴菜单,设置如下:

<div class="subCat" data-role="collapsible">
    <h3 title="someTitle">Subcategory Name</h3>
    <div class="itemImg">
        <img alt="Item 1" src="[image location]" /><span>Item 1</span>
    </div>
    <div class="itemImg">
        <img alt="Item 1" src="[image location]" /><span>Item 1</span>
    </div>
</div><!--End of subCat-->

Which goes on for several subcategories. I have a bit of code to get both the subcategory name and the title attribute from the image when clicked.

这适用于几个子类别。我有一些代码可以在单击时从图像中获取子类别名称和标题属性。

var currCat=$(this).closest('.subCat').children('h3').text();
var titleData=$(this).closest('.subcat').children('h3').attr("title");

"this" being the image that's clicked. currCat gets the proper string that it needs, but I'm always getting "undefined" for titleData. Not sue what's going wrong with getting the title.

“这个”是被点击的图像。currCat 获取它需要的正确字符串,但我总是为 titleData 获取“未定义”。不起诉获得标题出了什么问题。

回答by Sampson

Your second line has subcatinstead of subCat. The following should work:

你的第二行有subcat而不是subCat. 以下应该工作:

$(this).closest('.subCat').children('h3').attr("title");

Thank you for reminding me that classNames are case-sensitive in selectors. Easy thing to miss.

感谢您提醒我在选择器中 classNames 区分大小写。容易错过的事情。