简体   繁体   English

JavaScript函数调用无法通过链接进行

[英]Javascript function call doesn't work from a link

I try to call a custom made function from a link but somehow it doesn't work. 我尝试从链接中调用自定义函数,但是以某种方式不起作用。 Alert doesn't pop up. 警报不会弹出。 Help appreciated! 帮助赞赏! This is my code: 这是我的代码:

$.each(data.Tables, function(i, data){
    link = '<a href="#" onclick=test()>' + data.tableName + '</a>';
    tr.append("<td>" + link + "</td>");
    tr.append("<td>" + data.rowCount + "</td>");
    $("#tablesTable").append(tr);
});

This is my function: 这是我的功能:

function test (){
    alert("Doesn't work");
}

If I change the link row to this, alert comes after clicking the link. 如果我将链接行更改为此,则单击链接后会发出警报。

link = '<a href="#" onclick=alert()>' + data.tableName + '</a>';

JavaScript has no place in HTML attributes. JavaScript在HTML属性中没有位置。 jQuery can actually bind event handlers to elements even if they are not in the DOM, so I'd suggest you do something like this: jQuery实际上可以将事件处理程序绑定到元素,即使它们不在DOM中也是如此,因此我建议您执行以下操作:

$.each(data.Tables, function(i, data){
    var $link = $('<a></a>', { // Create a new jQuery object
        href: '#',
        html: data.tableName
    }).click(function(){
        // Your code here...
        alert("Doesn't work");
    });

    // We can't use '+' since $link is no longer a string
    tr.append($link.wrap('<td></td>').parent());

    tr.append("<td>" + data.rowCount + "</td>");

    $("#tablesTable").append(tr);
});

This uses jQuery to create the <a> tag, then uses .click() to bind the event. 这使用jQuery创建<a>标记,然后使用.click()绑定事件。

Change this 改变这个

link = '<a href="#" onclick=test()>' + data.tableName + '</a>';

to this 对此

link = '<a href="#" onclick="javascript:test();">' + data.tableName + '</a>';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM