首页 > 解决方案 > 如何在jquery中动态生成表达式?

问题描述

我有一个问题,我动态生成了复选框的名称,它进入了一个循环,我在名称中添加了循环 ID,并且为表的每一行生成了名称(仍然相同),我是试图在 jquery 中捕获这个变量,表达式很好,但是在运行代码时我收到错误“Uncaught Error: Syntax error, unrecognized expression:”,下面是我的 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 中创建和运行的。提前致谢。

标签: javascriptjquery

解决方案


你可以试试:

$(`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"/>


推荐阅读