【问题标题】:Unable to extract text from data attribute无法从数据属性中提取文本
【发布时间】:2017-10-02 10:49:15
【问题描述】:

我有每行包含一个编辑按钮的引导表。我使用了数据格式化程序来传递记录的 id,并带有一个可以在单击时提取的数据属性。当我在控制台中检查元素时,我可以看到 ID 在数据集属性中,但是当我尝试使用 element.dataset 将其取出时,控制台包含一个错误,告诉我数据集未定义。这很令人沮丧,因为我可以看到它就在那里!

这是我的点击事件:

$(".job-edit").click(function(event) {
    var editModal = $("#jobEditModal");
    var clicked = $(event.target);
    var id = clicked.dataset.jobid;
    console.log(id);
    event.stopPropagation();
    //editModal.modal(); 
});

以及设置按钮的格式化程序:

job.editFormatter = function (value) {
    return "<button class='btn job-edit text-center' data-jobId='" + value + "'><i class='fa fa-pencil-square-o' aria-hidden='true'></i> Edit</button>";
}

到目前为止,我已经尝试将.dataset 替换为.getAttribute(),但这也不起作用,我还尝试将jobid 的大小写更改为jobId,过去我不确定什么可能导致问题。

【问题讨论】:

  • 试试-clicked.data('jobid')clicked.attr('data-jobid')

标签: javascript jquery bootstrap-table


【解决方案1】:

而不是使用dataset,您可以直接使用.data() 的jquery 方法获得jobid,如下所示。您将获得数据集的未定义值,因为clicked 变量是一个jquery 对象,它没有dataset的定义

$(".job-edit").click(function(event) {
    var editModal = $("#jobEditModal");
    var id = $(this).data("jobid");
    console.log(id);
    event.stopPropagation();
    //editModal.modal(); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='btn job-edit text-center' data-jobId='2'><i class='fa fa-pencil-square-o' aria-hidden='true'></i> Edit</button>

【讨论】:

    【解决方案2】:

    您的问题是因为 clicked 是一个没有 dataset 属性的 jQuery 对象。

    要解决此问题,您需要使用本机元素引用:

    var id = e.target.dataset.jobid;
    

    或者,使用 jQuery 对象的data() 方法:

    var id = clicked.data('jobid');
    

    【讨论】:

    • 使用jobIdid 作为未定义在控制台。这不应该是jobid吗?
    • @Niladri 你是对的。大写“Id”是我的打字习惯:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多