javascript - Calling a function with parameters in href attribute - Stack Overflow

I'm calling a function with one parameter from an innerHTML property but nothing was displayed thi

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
Add a ment  | 

3 Answers 3

Reset to default 4

Try 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 inside htmlElement

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信