javascript - 如何在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 中创建和运行的。提前致谢。
解决方案
你可以试试:
$(`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"/>
推荐阅读
- javascript - 减少中的连接不起作用?
- android - Firebase 回收器视图适配器
- computer-vision - 平均 SIFT 特征进行姿态估计
- php - 如何按条件过滤内爆结果?
- python - 多处理:主进程未终止
- c++ - boost multi_index - 如果元素的类型是仅移动,如何将元素从一个容器添加到另一个容器?
- python - face_recognition knn 算法:是否可以在生成的 .clf 文件中添加更多面孔而不必再次重新训练所有内容?
- php - Apache 重写规则擦除全局 $_SERVER['request-uri']
- spring - 首次登录时,部署的 Spring App 未路由到正确的 URL
- c# - C# Newtonsoft.Json 无法解析日期