Cannot call javascript function in dynamically generated HTML

I cannot call a javascript function with a parameter in dynamically generated HTML code.

The same function is successfully called when I do not pass any parameter, but with the parameters that caused the function to be called. Not sure if this is a syntax error.

below is my code:

    <!DOCTYPE html>
    <html>
        <body>

            <p>Click the button to call a function with arguments</p>
            <button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

            <script>
            function myFunction(name,job) {
                var name="prasad";
                var str='<a href="#" onclick="javascript: fun('+name+')">link</a>';
                document.write(str);
            };

            function fun(id1) {
                alert("fun menthod "+id1);
            }
            </script>
        </body>
    </html>

If I do not pass the parameter, it will be called successfully.

+4
source share
4 answers
<!DOCTYPE html>
<html>
<body>
<div id="next">
<p>Click the button to call a function with arguments</p>
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
</div>
<script>
function myFunction(name,job)
{
var a='"';
a=a+name+a;
var str="<a href='#' onclick='fun("+a+")'>link</a>";
document.getElementById('next').innerHTML=str;
}
function fun(id1)
{
alert("fun menthod "+id1);
}
</script>
</body>
</html>
+1
source

Delete this line as the variable name matches the parameter name

var name="prasad";
+1
source

: var name="prasad"; 'name', , . .

0

change the name to:

var name="'prasad'";

I see a syntax error in the JS console otherwise.

0
source

All Articles