【问题标题】:jQuery: Create anchor with an object of data as a data attributejQuery:使用数据对象作为数据属性创建锚点
【发布时间】:2014-08-21 00:49:10
【问题描述】:

我在使用数据对象 (patientData) 作为数据患者属性创建锚点时遇到问题。示例打击显示了我正在尝试做的事情。 jQuery 文档声明您可以传递 .data() 名称和对象,但我无法设置它。

http://api.jquery.com/data/

我尝试了许多不同的方法。他们不使用任何 .serialize() 或 JSON.stringify()。我认为这是一个简单的错误,或者我错过了一些重要的东西。注释“//”是我尝试将“数据患者”属性设置为数据对象的一些旧方法。

// Define patient data as object
var patientData = {};
if (appt.appt_id) patientData.appt_id = appt.appt_id;
if (appt.enc_id) patientData.enc_id = appt.enc_id;
if (appt.person_id) patientData.person_id = appt.person_id;

var patientAnchor = $('<a />', {
    href: myUrl,
    html: patientHtml,
    class: 'apptSet',
//    'data-patient': JSON.stringify(patientData),
//    'data-appt_id': (appt.appt_id) ? appt.appt_id : null,
//    'data-enc_id': (appt.enc_id) ? appt.enc_id : null,
//    'data-person_id': (appt.person_id) ? appt.person_id : null,
    'data-ajax': 'true'
}).data('patient', patientData);

console.log(patientAnchor);

编辑:我刚刚注意到这个例子来自:

http://api.jquery.com/data/

在示例中,他们使用带有对象数据的 DIV。

$( "div" ).data( "test", { first: 16, last: "pizza!" } );

【问题讨论】:

    标签: jquery jquery-mobile


    【解决方案1】:

    您确定数据属性不起作用吗?您将 patientData 作为任何空对象,因此如果未定义 appt 属性,patientData 仍将为空:

    if (appt.appt_id) patientData.appt_id = appt.appt_id;
    if (appt.enc_id) patientData.enc_id = appt.enc_id;
    if (appt.person_id) patientData.person_id = appt.person_id;
    

    尝试执行以下操作以查看患者的数据:

    console.log(patientAnchor.data('patient'));
    

    另外,尝试静态设置,看看是否有效:

    .data('patient', {appt_id: 12, enc_id: 23, person_id: 3);
    

    【讨论】:

    • 是的,始终设置 appt_id。其他两个是可选的。我会根据您的建议运行 JSFiddle。
    • Console.log() 工作。 JSFiddle:jsfiddle.net/BLeQ9/7 但是,我如何查看 Google Chrome 的“检查元素”中的数据?它不会出现在元素的 HTML 属性或元素属性中。还是我错过了它? 'data-ajax' 显示在 'dataset: ajax' 下
    猜你喜欢
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多