我在CoffeeScript文件中有这个代码。基本上,我正在等待点击事件的响应,以填充一堆内容li
的内容。 但是我需要使用jQuery抓取这些元素并处理另一个点击事件
正如代码目前所示,底层jQuery无法正常工作,因为元素不在页面上。
任何帮助都会非常感激!
$ ->
chrome.tabs.query("active": true, "currentWindow": true,
(tab) ->
chrome.tabs.sendMessage(tab[0].id, "showTerms",
(response) ->
console.log (JSON.stringify(response))
terms = response
for term in terms
$(".terms").append($('<li></li>', {"class": "term", "data-term": "#{term}", "text": "#{term}"} ))
for child in $(".terms").children()
$(child).append($('<a></a>', {"href": "#", "class": "remove-term", "text": "x"} ))
)
)
$(".terms li a").click (e) =>
debugger
e.preventDefault()
termToBeRemoved = e.parent().data("term")
chrome.tabs.query("active": true, "currentWindow": true,
(tab) ->
chrome.tabs.sendMessage(tab[0].id, "remove" + termToBeRemoved,
(response) ->
console.log response
)
)
答案 0 :(得分:0)
您可以在加载元素时将点击事件附加到元素:
$ ->
chrome.tabs.query("active": true, "currentWindow": true,
(tab) ->
chrome.tabs.sendMessage(tab[0].id, "showTerms",
(response) ->
console.log (JSON.stringify(response))
terms = response
for term in terms
$(".terms").append($('<li></li>', {"class": "term", "data-term": "#{term}", "text": "#{term}"} ))
for child in $(".terms").children()
$(child).append($('<a></a>', {"href": "#", "class": "remove-term", "text": "x"} ))
#Bind them here after they've been created.
$(".terms li a").click (e) =>
debugger
e.preventDefault()
termToBeRemoved = e.parent().data("term")
chrome.tabs.query("active": true, "currentWindow": true,
(tab) ->
chrome.tabs.sendMessage(tab[0].id, "remove" + termToBeRemoved,
(response) ->
console.log response
)
)
)
)