Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取html属性时Jquery.data()方法不起作用_Javascript_Jquery_Html - Fatal编程技术网

Javascript 获取html属性时Jquery.data()方法不起作用

Javascript 获取html属性时Jquery.data()方法不起作用,javascript,jquery,html,Javascript,Jquery,Html,出于某种原因,jquery.data方法只有在使用jquery设置数据时才起作用。尝试检索html中设置的数据属性会导致返回值为null或未定义。这是我的javascript和html var ico = "<span class='deleteTag'></span>"; var x = "<span class='usertag' data-id='" + ui.item.userid + "'>" + ui.item.label+ " " + ico +

出于某种原因,jquery.data方法只有在使用jquery设置数据时才起作用。尝试检索html中设置的数据属性会导致返回值为null或未定义。这是我的javascript和html

var ico = "<span class='deleteTag'></span>";
var x = "<span class='usertag' data-id='" + ui.item.userid + "'>" + ui.item.label+ " " + ico + "</span>";
$("#" + id + " .userEditor").prepend(x);

$("#" + id + " .userEditor .deleteTag").bind("click",function(){
    alert($(this).parent().attr("data-id"))
    alert($(this).parent().data("id"));
    alert($("#testdivv").data("hola"));
    $(this).parent().data("yolo","swag");
    alert($(this).parent().data("yolo"));                                     
    // $(this).parent().remove();
});
这是一张工作票

它在Chrome中对我有效

    $(document).ready(function(){

    var id = "editor1";
    var ui = { 
                item: { userid : "user1", label: "some label" }
             };

    var ico = "<a href='#' class='deleteTag'>ClickThisDeleteTag</a>";
    var x = "<span class='usertag' data-id='" + ui.item.userid + "'>" + ui.item.label+ " " + ico + "</span>";

    $("#" + id + " .userEditor").prepend(x);

    $("#" + id + " .userEditor .deleteTag").bind("click",function(){
        $("#answer").html($(this).parent().data("id"));
    });

});

使用$element.attr'data-id';获取html属性。jQuery的数据不仅仅是读取属性:将JS代码放在就绪处理程序中:`$document.readyfunction{your code here};这也可能有帮助:您使用的是什么版本的jQuery?
    $(document).ready(function(){

    var id = "editor1";
    var ui = { 
                item: { userid : "user1", label: "some label" }
             };

    var ico = "<a href='#' class='deleteTag'>ClickThisDeleteTag</a>";
    var x = "<span class='usertag' data-id='" + ui.item.userid + "'>" + ui.item.label+ " " + ico + "</span>";

    $("#" + id + " .userEditor").prepend(x);

    $("#" + id + " .userEditor .deleteTag").bind("click",function(){
        $("#answer").html($(this).parent().data("id"));
    });

});