简体   繁体   English

通过动态创建的链接将参数动态传递给JavaScript

[英]Passing parameters to JavaScript dynamically from dynamically created link

I am trying to pass an array variable to my JavaScript method captureDetails() . 我试图将数组变量传递给我的JavaScript方法captureDetails() However, it is throwing me error 但是,这使我出错

Uncaught SyntaxError: Unexpected identifier 未捕获的SyntaxError:意外的标识符

What am I doing wrong? 我究竟做错了什么? I tried everything whatever is mentioned in other related posts, but no luck. 我尝试了所有其他相关文章中提到的所有内容,但是没有运气。

if (event.status) {
    $("#targetId").empty();
    $("#targetId").append("<ul>Please select if this is your organisation</ul>");
    for(var i = 0; i < result.length; ++i){

        var li = "<li><a href=\"#\" onclick=\"return captureDetails("+result[i]+");\">";
        $("ul").append(li.concat(result[i].Name))
    }
} 

The problem here is the unformatted inline event handler, which creates a invalid syntax. 这里的问题是未格式化的嵌入式事件处理程序,该处理程序创建了无效的语法。

A more appropriate solution here will be is to use event delegation along with data-* api to store the data. 这里更合适的解决方案是将事件委托与data-* api一起使用来存储数据。

 //just for testing purpose var event = { status: true }, result = [{ name: 'abc', id: 1 }, { name: 'asdf', id: 2 }] if (event.status) { $("#targetId").html("Please select if this is your organisation"); var $ul = $('<ul />'); for (var i = 0; i < result.length; ++i) { var $li = $('<li />').appendTo($ul); $('<a />', { text: result[i].name }).data('obj', result[i]).appendTo($li) } $("#targetId").append($ul) } //in dom ready handler $("#targetId").on('click', 'ul a', function() { var obj = $(this).data('obj'); snippet.log('clicked on: ' + JSON.stringify(obj)); }); 
 <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <!-- To show result in the dom instead of console, only to be used in the snippet not in production --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="targetId"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM