0

我的 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
        )
    )
4

1 回答 1

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
                  )
              )
        )
      )
于 2013-03-25T15:10:30.967 回答