简体   繁体   English

如何从此Javascript / jQuery函数访问HTML属性?

[英]How can I access a HTML attribute from this Javascript/jQuery function?

I have the following 我有以下

<div id="entries_list">
    <div id="entry_51" class="entry" data-entry_id="51">
        some text
    </div>
</div>

I am making entries_list sortable using jQuery UI . 我正在使用jQuery UI使entries_list 可排序 I need to do something when the user 'drops' an entry div, which can be done by: 当用户“删除”条目div时,我需要执行以下操作:

$("#entries_list").sortable({
    stop: function(event, ui) {
        console.log(ui);
    }
});

What is the easiest way to access the data-entry_id attribute of the entry div from within the stop function? stop函数中访问条目div的data-entry_id属性的最简单方法是什么? The console ouput of ui looks like this: ui的控制台输出如下所示:

在此处输入图片说明

尝试

alert(ui.item.attr("data-entry_id"));

ui.item is provided as a jquery object, so you can directly do ui.item.data('data_entry') ui.item是作为jquery对象提供的,因此您可以直接执行ui.item.data('data_entry')

$("#entries_list").sortable({
    stop: function(event, ui) {
        console.log( ui.item.data('entry_id') );
    }
});

will put 51 to the console in this example . 在本示例中,51放置到控制台

demo at http://jsfiddle.net/gaby/jKPty/ 演示在http://jsfiddle.net/gaby/jKPty/

Use the .data() function - http://api.jquery.com/data/ . 使用.data()函数-http: //api.jquery.com/data/ Note that HTML5 "data-" attributes are specified without the leading "data-" (hence, just "entry_id"). 请注意,指定的HTML5“ data-”属性不带前导“ data-”(因此仅是“ entry_id”)。

ui.item.data("entry_id")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM