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

后端 未结 8 2184
迷失自我
迷失自我 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 01:15

    Directly use:

    test('elem[i].url') 
    

    instead of:

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

    to pass the string inside a method.

    0 讨论(0)
  • 2021-02-09 01:16

    If I didn't misunderstand your question, here is your answer;

    var elem=[  {"name":"husain","url":"http://google.com","age":21},
        {"name":"ismail","url":"http://yahoo.com","age":22},
        {"name":"nambi","url":"http://msn.com","age":23}
    ]
    
    jQuery(function($){
        var str="";
        for(i=0;i<elem.length;i++){
            var a =$('<a>',{href:'#',text:'dd'});
            a.click(function(e){
                   test(elem[i].url)
            });
            $('.mytest').append(a).append($('</br>')).append($('</br>'));
    
        }
    });
    
    function test(url){
        console.log("url is "+url);
    }
    
    0 讨论(0)
提交回复
热议问题