问题描述
Jquery:
code> $(input:checkbox:not(:checked))。each(function(){
var columnName = $(this).attr('name');
$ ('td:nth-child('+ columnName +'),th:nth-child('+ columnName +')')。hide();
});
$(input:checkbox)。click(function(){
var columnName = $(this).attr('name');
$('td :nth-child('+ columnName +'),th:nth-child('+ columnName +')')。toggle();
});
HTML:
< input type =checkboxname =1checked =checked/>
当我将值放入:nth-child(1)时有效,但当包含变量。我做错了,或者我使用了错误的Jquery库。
任何帮助将不胜感激!
我猜你有一个或多个< input type =checkbox/>
其中 name
属性是不是一个数字,或者不存在。
例如:
< input type =checkboxname =string/>
使用您的代码时,会输出您描述的错误:
未捕获的错误:语法错误,无法识别的表达式::nth-child
解决方法是检查 columnName
是否为有效数字:
var columnName = $(this).prop('name')|| 0’ ;
$ b $ if(columnName.match(/ ^ [1-9] \d * $ /)){
// columnName必须以1到9之间的数字开始
//并且可以处理零个或多个数字
}
另外,它会将 class
分配给用于 show / hide
相应的<$ c $的复选框是一个更好的主意C> TD /日的。
< input type =checkboxclass =showHidename =1/>
这样,您只需选择/循环所需的元素,而不是选中每个复选框
$('input.showHide')。click(function(){...});
I've used someone else's answer to get this.
Jquery:
$("input:checkbox:not(:checked)").each(function() {
var columnName = $(this).attr('name');
$('td:nth-child(' + columnName + '),th:nth-child(' + columnName + ')').hide();
});
$("input:checkbox").click(function() {
var columnName = $(this).attr('name');
$('td:nth-child(' + columnName + '),th:nth-child(' + columnName + ')').toggle();
});
HTML:
<input type="checkbox" name="1" checked="checked"/>
It works when I put values in the :nth-child(1) but not when I include the variable. Am I doing it wrong or am I using the wrong Jquery library.
Any help would be appreciated!
I'm guessing you have one or more <input type="checkbox" />
where the name
attribute is not a number, or is not present.
For example:
<input type="checkbox" name="string" />
When using your code, this outputs the error you described:
Uncaught Error: Syntax error, unrecognized expression: :nth-child
See fiddle
A workaround would be to check that columnName
is a valid number:
var columnName = $(this).prop('name') || '0';
if (columnName.match(/^[1-9]\d*$/)) {
// columnName must start with a number between 1 to 9
// and can be proceeded by zero or more numbers only
}
Also, it would be a better idea to assign a class
to the checkboxes which are used to show/hide
the corresponding td/th's
.
<input type="checkbox" class="showHide" name="1" />
That way, you're only selecting/looping over the elements you want, and not every checkbox on the page.
$('input.showHide').click(function() { ... });
这篇关于Jquery:语法错误,无法识别的表达式:nth-child()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!