簡體   English   中英

使用復選框JS的名稱屬性更改事件

[英]change event using name attribute of checkbox JS

我有多個具有相同名稱屬性的復選框: myTask

<input type="checkbox" class="sol-checkbox" name="myTask" value="1B">
<input type="checkbox" class="sol-checkbox" name="myTask" value="2B">
<input type="checkbox" class="sol-checkbox" name="myTask" value="3B">

每次用戶單擊復選框時,我都會執行此jQuery代碼

$("input[name='myTask'").change(function(){
   alert(1);
});

我的腳本有什么問題嗎?

請檢查您的代碼中可能有問題。 你忘了加一個方括號

 $("input[name='myTask']").change(function(){ alert($(this).val()); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" class="sol-checkbox" name="myTask" value="1B"> <input type="checkbox" class="sol-checkbox" name="myTask" value="2B"> <input type="checkbox" class="sol-checkbox" name="myTask" value="3B">

您忘記添加一個右方括號。

請嘗試以下代碼。

通過輸入類型觸發 on 變化的方式。

// Shorthand for $( document ).ready()
$(function() {
    console.log( "ready!" );
    $("input[name='myTask']").change(function(){
        alert($(this).val());
    });
});

通過輸入字段的 class 名稱觸發 on change 的方式。

// Shorthand for $( document ).ready()
$(function() {
    console.log( "ready!" );
    $(".sol-checkbox").change(function(){
        alert($(this).val());
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM