我正忙于一个带有几个按钮和一个弹出窗口的小型 jquery 移动网络应用程序。这些按钮有一个带有 ID 的 data-id
属性。当我单击按钮时,将打开一个弹出窗口,但我不知道如何获取 data-id
值..
弹出内容将在调用popupbeforeposition
事件时设置。该内容将通过带有 ID 的 ajax 调用来检索(来自按钮;data-id
)。
我使用简单版本的 web 应用程序创建了一个 JSFiddle:http://jsfiddle.net/yW2PZ/1/
<div data-role="page">
<div data-role="content">
<div data-role="popup" id="media-edit-file" data-overlay-theme="a">
Popup
</div>
<a data-id="1" href="#media-edit-file" data-role="button" data-transition="flip" data-rel="popup">click me</a>
<a data-id="2" href="#media-edit-file" data-role="button" data-transition="flip" data-rel="popup">or me</a>
</div>
</div>
$(document).on('popupbeforeposition', '#media-edit-file', function(event, ui)
{
// how do I get the data-id value.. ?
});
最佳答案
考虑将您的处理程序绑定(bind)到 click
事件a
标签代替。这样,data-id
属性可通过 $(this)
访问回调函数的对象。然后,您可以使用 popup()
以编程方式打开弹出窗口方法。
例如:
$(document).on('click', 'a', function(event, ui) {
var data_id = $(this).data('id');
// ... fetch the popup's content ...
$('#media-edit-file').popup('open');
});
<小时/>
有关访问 HTML5 数据属性的更多信息
注意data-id
是如何属性通过 data()
访问方法为id
,自 data-
当 jQuery 自动将 HTML5 属性添加到元素的 data()
时,前缀会被省略。目的。例如,这也意味着 data-rel
也可以通过 data('rel')
访问。有关 data()
的更多信息方法见jQuery Manual .
关于jquery - 从触发另一个元素事件的单击元素中检索数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14427829/