Passing a string in onclick function's attribute of element dynamically created element

后端 未结 8 2179
迷失自我
迷失自我 2021-02-09 00:27

I am trying to pass a string in the onClick event handler function\'s arguments of the dynamically created anchor element, see the fiddle http://jsfiddle.net/shmdhussain/bXYe4/.

相关标签:
8条回答
  • 2021-02-09 00:50

    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.

    0 讨论(0)
  • 2021-02-09 00:54

    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+="<a href='#' onclick='test(\""+elem[i].url+"\")'>dd</a><br/><br/>";
    

    This will generate a html like this:

    <a href='#' onclick='test("your_url")'>dd</a><br/><br/>
    
    0 讨论(0)
  • 2021-02-09 00:55

    Directly use:

    test('"+elem[i].url+"') 
    

    instead of:

    'test('"+elem[i].url+"')' 
    

    to pass the string inside a method.

    0 讨论(0)
  • 2021-02-09 00:57
    var funcName = "SelectPickerBtnSelectEvent('" + str + "')";
    $(".btn.dropdown-toggle.btn-light").attr("onclick", funcName);
    
    0 讨论(0)
  • 2021-02-09 00:58

    You have to use proper string sytax. This

    "<a href='#' 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.

    "<a href='#' onclick='test(\""+elem[i].url+"\")'>dd</a><br><br>"
    

    Which results in

    <a href='#' onclick='test("http://domain.tld")'>dd</a><br><br>
    
    0 讨论(0)
  • 2021-02-09 01:03

    perhaps instead, use a data attribute on the element to hold the string. then in the function retrieve the data.

    0 讨论(0)
提交回复
热议问题