簡體   English   中英

如何在 jquery 中動態生成表達式?

[英]how to dynamically generate expression in jquery?

我有一個問題,我動態生成了復選框的名稱,它在一個循環中,我在名稱中添加了循環 ID,並且為表的每一行生成了名稱(仍然相同),我是試圖在 jquery 中捕獲這個變量,表達式很好,但是在運行代碼時我收到錯誤“未捕獲的錯誤:語法錯誤,無法識別的表達式:” ,下面是我的 Jquery 代碼:

 $('.select_all').on('click',function(){
        var id = $(this).attr('id');
        console.log("inside select all click id is :" + id)
        var cbox = "'"+id+"checkBox"+"'";
        var c ="\"input[name="+cbox+"]\"";        
        if($("#" + $(this).attr(id) + " INPUT[type='checkbox']").attr('checked', true)){
            console.log("inside this");         
            $(c).each(function(){
                console.log("inside ckbox")
              this.checked = true;                
        });         
        }else{
            $(c).each(function(){
                this.checked = false; 
            });
            
        }   
 });

這里變量 c 的形式類似於“input[name='1checkBox']” ,這是正確的,但是當涉及到 $(c).each 部分時,它會引發上述錯誤。 有人能告訴我動態表達式是如何在 jquery 中創建和運行的嗎? 提前致謝。

你可以試試:

$(`input[name='${cbox}']`)

例子:

 const name= "password" console.log($(`input[name="${name}"]`)[0])
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input name="password"/>

去掉包圍選擇器的多余的"標記:而不是

var c ="\"input[name="+cbox+"]\"";        

簡單地做

var c ="input[name="+cbox+"]";        

我可以通過更改代碼來解決我的問題,下面是我使用的 JS 代碼。

$('.select_all').on("click", function(event) {
     console.log("inside event propogation")
        event.stopPropagation();
    });

$('.select_all').on('click',function(){
    var id = $(this).attr('id');        
    var cbox = "'"+id+"checkBox"+"'";   
    if(this.checked) {                  
        $("[name="+cbox+"]").each(function(){               
          this.checked = true;                
    });         
    }else {
        $("[name="+cbox+"]").each(function(){       
             this.checked = false;
            
        });
    }               

});

暫無
暫無

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

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