使用 jQuery 检索属性中的文本
Retrieve text within an attribute using jQuery?
对于开始,我有这个HTML和示例数据:
<div class="card {toggle:'someinformation'}">
<div class="off"></div>
<div class="on {toggle:'getThisInfo'}"></div>
</div>
我想使用 jQuery 并检索此信息。在询问某人时,他们告诉我使用以下方法(这不起作用):
var $card = $(this);
var this_card = $card.children(".on").metadata()["toggle"];
并被告知"this_card"的值将是"getThisInfo" - 它不起作用。是的,我确实确保元数据也包含在HTML和jQuery中。
还有其他建议吗?
只需使用 HTML5 data-*
属性:
<div class="card" data-toggle="someinformation">
<div class="off"></div>
<div class="on" data-toggle="getThisInfo"></div>
</div>
然后使用 jQuery 的 .data()
函数访问它,如下所示:
var $card = $(this),
this_card = $card.children(".on").data("toggle"); // "getThisInfo"
更新:
根据发布的额外代码,这应该非常适合您:
var $on_cards = $(".card > .on:visible");
if ($on_cards.length == 2) {
var $card = $('.card:first'), // was $(this), replaced just for this demo
this_card = $card.children(".on").data("toggle"),
$matched_cards = $on_cards.filter('[data-toggle="' + this_card + '"]'),
event_name = "no_match";
if ($matched_cards.length === 2) {
event_name = "found_match";
}
}
这使用 jQuery 的属性等于选择器来查找具有相同data-toggle
值的.on
元素。
重要提示:如果您需要更改.on
的值,则不要使用 jQuery 的 .data()
函数来执行此操作,请使用:
$(selector).attr('data-toggle','your-new-value');
这是因为.attr()
和.prop()
更新 HTML 中的属性([data-toggle=""]
选择器检查),而.data()
更新内部 jQuery 对象而不影响实际元素。
它在这里工作:http://jsfiddle.net/c4fQ3/1/(尝试更改.on
元素的data-toggle
值)
相关文章:
- 如何在弹出窗口中隐藏文本属性'It’传单上没有填写
- FabricJS CurvedText对象(扩展)在更新间距和文本属性时未显示
- jQuery文本属性中的Html代码
- jQuery 控件的 AJAX 文本属性成功,返回 [对象对象]
- 我可以在Javascript的DOM节点中存储非文本属性吗?
- 如何平展对象文本属性
- D3:x 轴上的日期名称:<文本>属性 x=“NaN”的值无效
- 检查对象文本属性的名称
- 在javascript更新后,从web用户控件获取codebehind中的asp:TextBox文本属性
- 文本属性输入框,用于选择字体
- D3圆包:html文本属性
- Javascript /jquery-如何检查一个元素是否有文本属性
- JointJS模型-文本属性没有被分配
- Raphaeljs Substring文本属性
- Textarea值和文本属性在react中没有定义
- javascript更新后,Asp文本框文本属性不正确
- 显示来自数据文本属性的数据
- 无法使用函数更改d3.js中的文本属性(“y”)
- 使用javascript在客户端的gridview中设置标签控件文本属性
- Angular + d3.js:使用SVG文本属性进行数据绑定