为 kendo 网格列模板中的全局变量分配动态值

Assigning dynamic value to a global variable in kendo grid column template

好的,现在我有了这个 Kendo 网格代码:

var ds = [
    { "ID" : 1, "attach" : "true", "attachment" : "http://www.google.com" },
    { "ID" : 2, "attach" : "false", "attachment" : "" },
    { "ID" : 3, "attach" : "true", "attachment" : "http://www.wikipedia.com" },
    { "ID" : 4, "attach" : "false", "attachment" : "" }
];

var $value = "asd";

var grid = $("#grid").kendoGrid({ 
    dataSource: ds,
    columns: [
        { field: "ID", Title: "ID", filterable: false, sortable: false, hidden: false },
        { field: "attach", Title: "Attached?", filterable: false, sortable: false, hidden: false},
        {
            title: "Attachment Link",
            template: '#if(attachment != ""){' +
                          '$value = attachment' +
                          '#<input type="button" class="info" value="IT WORKS" />' +
                      '#}else{#' +
                          '<label>NOPE</label>' +
                      '#}#',

            headerTemplate: "<label> Attachment </label>",
            sortable: false,
            filterable: false,
            width: 100
        }
    ]

}).data("kendoGrid");

//this is where I have been playing around trying to get the value. its not working. Shocker :D 
//I changed this part frequently, this is just the latest form I got it in. 

$(".info").on("click", function() {
        var row = $(this).closest("tr");
        var item = grid.dataItem(row);
        var show = $value;
        alert("The item is:" + show);
});

我检查一行的列是否有任何非空值,如果有,我在那里放置一个按钮。

当我尝试将值分配给附件时,('value = attachment' 部分)结果是未定义,但是如果我这样附上附件:

'#if(attachment != ""){#' +
                '#= attachment#' +
                '<input type="button" class="info" value="IT WORKS" />'
'#}else{#' +
                '<label>NOPE</label>' +
'#}#',

我可以打印分配给它的实际 link。当我单击与其关联的按钮时,如何获取附件的值(单独地,而不是列表或数组或其他)?

这里是fiddle:https://jsfiddle.net/phyrax/zz1h65f5/

提前致谢!

Kendo grid column template 是 HTML 内容的模板。

如果你想在 html 代码中放置一些元素,你应该使用模板。如我所见,您想在此模板中执行 JS 代码。为此,您应该在模板中定义 <script> $value = #= attachment# </script>

另一个问题是你想做什么,因为当你做这样的事情时,它会在页面加载期间对每一行执行。因此 $value 的值将始终设置为最后一行。

编辑第一条评论:

您应该考虑将模板定义为

<input type="button" class="info" value="IT WORKS" onclick="setAttachment('#= attachment#')" />

并在全局 JS 代码中定义函数

function setAttachment(attachmentValue)
{
   $value = attachmentValue;
}

这是解决这个任务更合适的方法。在单击触发器时执行操作,而不是立即执行。