![](/img/trans.png)
[英]Javascript - Issue with scope and passing parameters to dynamically created event handler
[英]Passing parameters to JavaScript dynamically from dynamically created link
我試圖將數組變量傳遞給我的JavaScript方法captureDetails()
。 但是,這使我出錯
未捕獲的SyntaxError:意外的標識符
我究竟做錯了什么? 我嘗試了所有其他相關文章中提到的所有內容,但是沒有運氣。
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))
}
}
這里的問題是未格式化的嵌入式事件處理程序,該處理程序創建了無效的語法。
這里更合適的解決方案是將事件委托與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.