admin管理员组

文章数量:1221302

I try to append this following tag which has an onclick function.

 $("body").append('<img onclick="removeDynamicColumn(this,'someString')" src="css/images/builder/removeTDTR.png"/>');

In this function I am passing two parameters one is, the element itself and another one is string , if I enclose that string parameter with single quotes in JSP itself showing this error -

Syntax error on token "someString", invalid AssignmentOperator.

If I enclose with double quotes while calling that function I got this error -

SyntaxError: expected expression, got end of script

I try to append this following tag which has an onclick function.

 $("body").append('<img onclick="removeDynamicColumn(this,'someString')" src="css/images/builder/removeTDTR.png"/>');

In this function I am passing two parameters one is, the element itself and another one is string , if I enclose that string parameter with single quotes in JSP itself showing this error -

Syntax error on token "someString", invalid AssignmentOperator.

If I enclose with double quotes while calling that function I got this error -

SyntaxError: expected expression, got end of script

Share Improve this question edited Apr 5, 2017 at 12:03 Pete 58.4k29 gold badges130 silver badges184 bronze badges asked Apr 5, 2017 at 9:01 hardcodehardcode 4051 gold badge4 silver badges20 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 6

Missing Escape '\' character in your code.

Try that code;

$("body").append('<img onclick="removeDynamicColumn(this,\'someString\')" src="css/images/builder/removeTDTR.png"/>');

Try escape \

 $("body").append('<img onclick="removeDynamicColumn(this,\'someString\')" src="css/images/builder/removeTDTR.png"/>');

let's assume we have an string in a variable like this:

var param = "somestring"

we can inject this variable to your example, this way:

$("body").append('<img onclick="removeDynamicColumn(this, \'' + param + '\')" src="css/images/builder/removeTDTR.png"/>');

G.L

You need to escape your quote marks.

Try using \ before the ' characters around someString.

\'someString\'

Why bind it like that - if you are using jQuery then you can use a delegated bind and then use data- attributes for your string:

var body = $("body");

// give your image a class and data attribute for your string
body.append('<img src="css/images/builder/removeTDTR.png" data-string="some string" class="click-image">')

// this is delegated bind
body.on('click', '.click-image', function() {
   var image = $(this),                  // your image as a jquery object
       someString = image.data('string'); // your string 
   // do your onclick action here
});

本文标签: javascriptPass this and string as parameter in jquery functionStack Overflow