Passing A String In Onclick Function's Attribute Of Element Dynamically Created Element
Solution 1:
You have to use proper string sytax. This
"<ahref='#'onclick='test('"+elem[i].url+"')'>dd</a><br><br>"
will result in
<a href='#' onclick='test('http://domain.tld')'>dd</a><br><br>
You cannot use ' for onclick and the parameters of test. Use \" instead.
"<ahref='#'onclick='test(\""+elem[i].url+"\")'>dd</a><br><br>"
Which results in
<ahref='#'onclick='test("http://domain.tld")'>dd</a><br><br>
Solution 2:
Your problem is, that str+="<a href='#' onclick='test('"+elem[i].url+"')'>dd</a><br/><br/>";
will return a string like "<a href='#' onclick='test('your_url')'>dd</a><br/><br/>"
. This will generate a html like this:
<a href='#' onclick='test('your_url')'>dd</a><br/><br/>
In this case, the onclick attribute contains only 'test('.
Try this:
str+="<ahref='#'onclick='test(\""+elem[i].url+"\")'>dd</a><br/><br/>";
This will generate a html like this:
<ahref='#'onclick='test("your_url")'>dd</a><br/><br/>
Solution 3:
Directly use:
test('"+elem[i].url+"')
instead of:
'test('"+elem[i].url+"')'
to pass the string inside a method.
Solution 4:
If I didn't misunderstand your question, here is your answer;
var elem=[ {"name":"husain","url":"http://google.com","age":21},
{"name":"ismail","url":"http://yahoo.com","age":22},
{"name":"nambi","url":"http://msn.com","age":23}
]
jQuery(function($){
var str="";
for(i=0;i<elem.length;i++){
var a =$('<a>',{href:'#',text:'dd'});
a.click(function(e){
test(elem[i].url)
});
$('.mytest').append(a).append($('</br>')).append($('</br>'));
}
});
functiontest(url){
console.log("url is "+url);
}
Solution 5:
For passing multiple parameters you can cast the string by concatenating it with the ASCII value like, for single quotes we can use '
var str= "'"+ str+ "'";
the same parameter you can pass to the onclick(str)
event.It is helpful in cases where we pass multiple parameters.It works with every browser.
Post a Comment for "Passing A String In Onclick Function's Attribute Of Element Dynamically Created Element"