I'm calling a function with one parameter from an innerHTML
property but nothing was displayed this is my code:
var myVar="Ali";
summaryPanel.innerHTML += "<a href='javascript:sayHello("+ myVar+");'>" + "Say Hello" + "</a>";
function sayHello(myVar)
{
window.alert(myVar);
}
I'm calling a function with one parameter from an innerHTML
property but nothing was displayed this is my code:
var myVar="Ali";
summaryPanel.innerHTML += "<a href='javascript:sayHello("+ myVar+");'>" + "Say Hello" + "</a>";
function sayHello(myVar)
{
window.alert(myVar);
}
Share
Improve this question
edited Jan 28, 2015 at 8:44
Ali Noureddine
asked Sep 1, 2014 at 17:04
Ali NoureddineAli Noureddine
3235 silver badges20 bronze badges
3
- You need to have a trigger for that function. Right now all you are doing is creating an HREF, with no actual trigger, and no closing tag. – durbnpoisn Commented Sep 1, 2014 at 17:06
- 1 Assuming the link can be clicked and it gets clicked: Have a look at the console. You'll see an error. Hint: string literal, quotation marks. – Felix Kling Commented Sep 1, 2014 at 17:09
- hey bro check out my answer it might help you – Bathri Nathan Commented Jul 8, 2019 at 6:24
3 Answers
Reset to default 4Try this:
var a = document.createElement('a');
a.appendChild(document.createTextNode('Click me'));
a.addEventListener('click', function() {
sayHello(myVar);
}, false);
summaryPanel.appendChild(a);
Some notes:
- Avoid inline event handlers, which require global functions
- Avoid polluting global scope
- Avoid building html elements from strings using untrusted variables (may be the case of
myVar
). This practice is vulnerable to html injection. - Avoid
htmlElement.innerHTML += something
. This will erase all data and event handlers added to previous elements insidehtmlElement
In order to use the function with parameter in href you need to escape the double quotes please refer the below syntax.
return "<a hreg ='javascript:void(0)' onclick='showErrorPopup(\""+message+"\")'>"+value+"</a>";
function showErrorPopup(message){
alert(message);
}
where i have used \ to escape the double quotes
Try this
var myVar = "Ali";
summaryPanel.innerHTML += "<a href='javascript:void(0)' onclick='sayHello("+myVar+")' />";
function sayHello(param){
windows.alert(param);
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744728376a4590317.html
评论列表(0条)