开发者

How to quote a string dynamically in Javascript?

This kinda funny, i want to quote a string value for a function but javascript throws this error Uncaught SyntaxError: Unexpected token }

This my code

var val = "Testing String";
var table_row = "<tr><td><a href='#' onclick='test('"+val+"')'>Row1</a></td></tr>";

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

The tab开发者_高级运维le row get created fine with the test function bound well with onClick event. But when i click on the created link i get

`Uncaught SyntaxError: Unexpected token }

The Value within the test function should be a quoted string.

Note: If i remove the concatenation of the val string, and pass is as a string like this

table_row = "<tr><td><a href='#' onClick='test(\"Testing String\")' >Row1</a></td>";

... it works

Where am i goofing?

Gath.


Then in your original script also escape ":

var test = "\"test string\"";


i thing it ll help u sir,,,,

if row1 is variable

u can add by '+Row1+' seperator,

or else directly use bellow code;

var table_row = '<tr><td><a href="#" onClick="test(\'Testing String\')" >Row1</a></td>';
        //alert("++++++++++++"+table_row+"++++++++++++");

see ya ,,,


Given

var val = "Testing String";
var table_row = "<tr><td><a href='#' onclick='test('"+val+"')'>Row1</a></td></tr>";

Should table_row not be

"<tr><td><a href='#' onclick='test('Testing String')'>Row1</a></td></tr>"

so the onclick attribute is only 'test(', because ' ends it?

Try:

var table_row = "<tr><td><a href='#' onclick=\"test('"+val+"')\">Row1</a></td></tr>";


This what i did and now working fine;

var val = "Testing String";
table_row = "<tr><td><a href='#' onclick='test(\""+val+"\")'>Row1</a></td></tr>";

function test( val ){
 alert( val)   // Displays "Testing String"
}

Thanks for your patience.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜