最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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);
}
发布评论

评论列表(0)

  1. 暂无评论