[英]How do I set a jQuery selector in coffeescript using a variable?
我正在編寫一個Rails應用程序,並且在同一頁面上有多種形式的表單都具有不同的ID。 在咖啡腳本中,我試圖設置標識符以訪問每個文本區域。 這是html在瀏覽器中的外觀的快速示例。
的HTML
<a href="#" class="link" data-plan="1">Click here</a>
<form id="new_item_plan_1">
<textarea id="plan_1_item_field"></textarea>
</form>
設置計划ID並嘗試訪問文本區域
plan_id = 0
$(".link").click ->
plan_id = $(this).data("plan")
$("#plan_"+plan_id+"_item_field").keypress ->
...Some code...
因此,我先初始化了plan_id
變量,然后將其設置為.link
的數據計划值。 但是我的按鍵事件在textarea上不起作用,並且在控制台中沒有出現錯誤。
當我建立測試鏈接並進行console.log
時...
plan_id = 0
$(".link").click ->
plan_id = $(this).data("plan")
$("#test).click ->
console.log(plan_id)
它會在控制台中正確打印正確的plan_id
值,因此我必須在textarea標識符中做錯了什么。 我怎么了 謝謝。
鏈接到jsfiddle,注意keypress事件如何不起作用https://jsfiddle.net/cfscr/175/
<a href="#" class="link" data-plan="1">Click here</a>
<form id="new_item_plan_1">
<textarea id="plan_1_item_field" class='item-field' data-plan='1'></textarea>
</form>
plan_id = 0
$(".link").click ->
plan_id = $(this).data("plan")
$(".item-field").keypress ->
if $(this).data('plan') == plan_id {
...Some code...
您可以在文本區域中使用正則表達式而不是其他data
標簽,我只是懶惰;)
您的代碼中發生的是按鍵綁定是在頁面加載時應用的,因此僅在計划ID仍為0時才應用一次。在plan_id更新時,它不會重新應用。
我應該注意,這樣做似乎很奇怪,但是您需要將綁定放入click事件中。 也就是說,你想要
$("#plan_"+plan_id+"_item_field").keypress ->
...Some code...
在每次觸發click事件時應用。 為此,必須正確縮進
plan_id = 0
$(".link").one 'click', ->
plan_id = $(this).data("plan")
$("#plan_"+plan_id+"_item_field").keypress ->
...Some code...
這樣可以使用戶多次單擊按鈕時,會將綁定應用於該按鍵。 這是您想要完成的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.