Jquery: Syntax error, unrecognized expression :nth-child()

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

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!

回答1:

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() { ... }); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!