简体   繁体   English

jQuery 附加 onclick 功能不起作用

[英]jQuery append onclick function doesn't work

I have problem with append function.我有附加功能的问题。 This code doesn't work properly.此代码无法正常工作。

$(element).append("<a onclick='test('test')'> <i class='fa fa-spin fa-pencil' aria-hidden='true'></i></a>");

test function:测试功能:

function test(value)
{
 alert(value);
}

I suspect that the problem is related to onclick function.我怀疑问题与 onclick 功能有关。

You have to escape apostrophes inside:你必须在里面转义撇号:

 $(element).append("<a onclick='test(\"test\")'> <i class='fa fa-spin fa-pencil' aria-hidden='true'></i></a>");

And make sure test() is defined globally (and not inside document ready for example).并确保test()是全局定义的(例如,不在文档内部准备好)。

Here is an example:下面是一个例子:

 window.test = function(value){ alert(value); }; $('div').append("<a onclick='test(\\"test\\")'>click me</a>");
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div></div>

As alluded to in the comments, you can't nest similar quote marks in a string like you are currently doing.正如评论中提到的,您不能像当前那样在字符串中嵌套类似的引号。 You need to escape them with a back slash:你需要用反斜杠来逃避它们:

 function test(value) { alert(value); } var element = $('body'); $(element).append("<a onclick='test(\\"test\\")'> <i class='fa fa-spin fa-pencil' aria-hidden='true'></i>Click Me</a>");
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Use ` quote instead of '使用 `quote 而不是 '

I created a jsbin here.我在这里创建了一个 jsbin。 II hope this is what you are trying to do我希望这就是你想要做的

http://jsbin.com/wicanok/edit?html,js,output http://jsbin.com/wicanok/edit?html,js,output

$('#element').append("<a onclick='test(`test`)'> <i class='fa fa-spin fa-pencil' aria-hidden='true'>Hi</i></a>");

You're better off taking that inline JS out altogether and using jQuery to add the event listener (using event delegation because you're adding new elements to the DOM).您最好完全去掉内联 JS 并使用 jQuery 添加事件侦听器(使用事件委托,因为您要向 DOM 添加新元素)。

$(element).append('<a class="test">...');

$(document).on('click', '.test', function () {
  test('test');
});

You can try this:你可以试试这个:

$(element).append("<a onclick='test('test')' class="your_class"> <i class='fa fa-spin fa-pencil' aria-hidden='true'></i></a>");
$(document).on('click',".your_class", function(){
//Write here your code!
});

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

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