简体   繁体   中英

Call a function with parameters in JavaScript append

I need to call a function with parameters in a jQuery append method and want to pass a variable named image but I keep getting syntax error even when I pass a static value

$("#officialDiv").append("<a onclick='remove('" + image + "');' class='btn btn-danger btn-sm'></a>");

or static

$("#officialDiv").append("<a onclick='remove('test');' class='btn btn-danger btn-sm'></a>");

function remove(file) {
}

below a screenshot of the error

在此处输入图片说明

That is because your HTML string is breaking on ' . You need to escape the quotes.

$("#officialDiv").append("<a onclick=\"remove(\'" + image + "\');\" class='btn btn-danger btn-sm'>Link</a>");

Should work fine.

Demo

 var image = "some_data"; $("#officialDiv").append("<a onclick=\\"remove(\\'" + image + "\\');\\" class='btn btn-danger btn-sm'>Link</a>"); function remove(a){ console.log(a+" is removed"); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="officialDiv"></div>

It appears the issue is probably within the image variable.

That said, we can use template literals to reduce the quotes confusion.

$("#officialDiv").append(`<a onclick="remove(${image});" class="btn btn-danger btn-sm">Image</a>`);

Here's a working example:

 var image = "myImage"; $("#officialDiv").append(`<a onclick="remove('${image}');" class="btn btn-danger btn-sm">Image</a>`); const remove = function(name) { alert(name); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="officialDiv"></div>

 var test = 'test'; $("#officialDiv").append("<a onclick='remove(test)' class='btn btn-danger btn-sm'>click me</a>"); function remove(file) { alert(file); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='officialDiv'></div>

How about this approach?

var anchor = $("<a class='btn btn-danger btn-sm'>click me</a>");
anchor.on('click', function () {
    remove(image)
});

$("#officialDiv").append(anchor);

function remove(file) {
    alert(file)
}

You could untie the behavior through an event handler thus removing the issue (additional benefit you get is cleaner, reusable code):

<a onclick="onRemoveClick()" ... >

function remove(value) { ... } 
function onRemoveClick() { remove('image'); }

就我而言,上述所有解决方案均未满足我的要求。

$('.my-list').append('<a href="javascript:openFile(\''+ dataId +'\')"><li class="list-group-item">'+ itemName +'</li></a>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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