在单页应用程序中访问动态创建的数据标记

时间:2015-11-06 13:50:56

标签: javascript jquery single-page-application kendo-template

我有一个单页面应用程序,它动态填充div,列表项将在点击时调用一个函数。我正在尝试动态填充数据标记,然后在附加的列表项中访问它。

$(\#documents)中的反斜杠是因为这是我的路由函数调用的kendoUI模板。

一旦从服务器检索到数据,就会在Ajax成功函数中调用构建树函数。任何见解或帮助表示赞赏!!!

   function buildTreeView(tree, jobCode){
       var treeHtml = "<div class='row'><div class='col-xs-12 col-sm-8 col-sm-offset-2'><div class='panel-group'><div class='panel panel-default'><div class='panel-heading'><h3 class='text-center'>View or Download Documents</h3></div><div class='panel-body'><ul class='list-group'>";
        for(var i =0;i < tree.length;i++){
          if(typeof tree[i] === 'object'){
            for(var ind = 0;ind < tree[i].length; ind++){
                //another element will be populated here
            }
          }else{
            treeHtml += "<li class='list-group-item viewDoc' data-docName='"+tree[i]+"' data-jobCode='"+jobCode+"'>"+tree[i]+"</li>";
          }
        }
        treeHtml += "</ul></div></div></div></div></div>";
        $('\#documents').append(treeHtml);
}

$(document).on("click", ".viewDoc", function(){
    var docName = $(this).data('docName');
    var jobCode = $(this).data('jobCode');
    console.log(docName);
    console.log(jobCode);
});

2 个答案:

答案 0 :(得分:0)

更改您的功能,以便使用.data(键,值)设置数据。见https://api.jquery.com/data/

function buildTreeView(tree, jobCode){
    $('\#documents').append("<div class='row'><div class='col-xs-12 col-sm-8 col-sm-offset-2'><div class='panel-group'><div class='panel panel-default'><div class='panel-heading'><h3 class='text-center'>View or Download Documents</h3></div><div class='panel-body'><ul class='list-group'></ul></div></div></div></div></div>");
    for(var i =0;i < tree.length;i++){
      if(typeof tree[i] === 'object'){
        for(var ind = 0;ind < tree[i].length; ind++){
            //another element will be populated here
        }
      }else{
        var li = $('\#documents').find('ul:last()').append("<li class='list-group-item viewDoc'>"+tree[i]+"</li>");
        $(li).data("docName",tree[i]);
        $(li).data("jobCode",jobCode);
      }
    } 
                // ---- EDITED ----//

    var li = $('\#documents').find('ul:last()').append("<li class='list-group-item viewDoc' id='docIndex"+i+"'>"+tree[i]+"</li>");
    $('\#docIndex'+i).data({"docName":tree[i], "jobCode":jobCode});    

答案 1 :(得分:0)

您无法访问这些数据,因为数据属性&#34; docName&#34;和&#34; jobName&#34;被标准化为小写。

例如,html看起来像这样:

<li class="list-group-item viewDoc" data-docname="something" data-jobcode="something">something</li>

在这里查看better answer

无论如何,这都有效:

$(document).on("click", ".viewDoc", function(){
    var docName = $(this).data('docname');
    var jobCode = $(this).data('jobcode');
    console.log(docName);
    console.log(jobCode);
});

更新:已添加jsfiddle