0

我有一个表,其中包含一个具有多个文件名的列。文件名实际上是链接,其中一些指向 URL,其中一些指向本地文件。当独立单击时,我可以成功下载本地文件并指向新窗口中的 url。

但是,当我尝试通过 js 中的函数传递文件名来动态执行此操作时href,我遇到了一个Uncaught SyntaxError: Unexpected token :. 当我只调用没有任何参数的 js 函数时,这似乎不是问题,但是,所有链接都指向列中的最后一个文件名。我可以在浏览器底部看到javascript:openLink(filename)正确的文件名,但随后发生错误。

桌子

这是我的代码:

function searchAjax(){
    var $table = $("#tableGrid").tablesorter(),
            $tbody = $table.children("tbody");
            $.ajax({
                dataType: 'json',
                url: 'table_results',
                type: 'GET',
                data: $('#filterForm').serialize(),
                success: function(data) {
                    $("#tableGrid").find("tr:gt(0)").remove();
                    $.each(data, function(index, result) {
                        function openLink(value){
                            var link = value;
                            if(link.indexOf("http") > -1 ){
                                window.open(link, "_blank");
                            }
                            else{
                                location.href="/projectv1?fileName="+link;
                            }
                        };
                        $tbody.append(
                                "<tr>" +
                                "<td>" + result.regionCode + "</td>" +
                                "<td>" + result.nationCode + "</td>" +
                                "<td>" + '<a href="javascript:openLink('+result.link+')" target="_blank">link</a></td>"' +
                                "</tr>");

                    });
                        $("#tableGrid").trigger("update");
                }
            });
        };
4

1 回答 1

2

您可以像这样更改您的 html 附加代码

$tbody.append(
    "<tr>" +
    "<td>" + result.regionCode + "</td>" +
    "<td>" + result.nationCode + "</td>" +
    "<td>" + '<a class="customLink" data-url="'+result.link+'">link</a></td>"' +
    "</tr>");

您可以将点击事件处理程序添加到您的 customLink 。

$(this).data('url') 从 html 元素的 data 属性中检索链接数据。

jQuery(document).on(
{    
    click: function(e) 
    {
        var url = $(this).data('url');
        openLink(url);
    }
}
, '.customLink');

您还应该将您的 openLink 函数定义移动到外部范围

于 2014-10-14T07:39:27.230 回答