Unclosed square bracket doesn't throw error in jquery

和自甴很熟 提交于 2020-04-16 02:44:45

问题


$('#parent_tab [href="#tab1"').click();

The above line works fine and the tab gets selected in other browsers but not safari. I had to close the square bracket of href as follows in order to make it work in Safari.

$('#parent_tab [href="#tab1"]').click();

Why did jquery not throw an error when the square bracket is not closed?


回答1:


This looks like it's a Safari issue. Another reason is because the closing bracket is inside the jQuery selector. Safari might be concerned only with JavaScript code outside jQuery selector. It is just a text that can have different format and jQuery just tries to interpret it.

You can also try the following code if it will throw an error.

$("#parent_tab [href='#tab1'").click();



回答2:


The CSS spec says that it's okay to leave off the bracket. Since jQuery passes the selector along to the native querySelectorAll first for performance, and that method does not throw an error (plus it returns the correct element), the missing bracket isn't detected. If you used a jQuery-specific selector like :animated the string would go through jQuery's Sizzle selector engine and you would get an error.

https://bugs.jquery.com/ticket/15199




回答3:


I was getting exactly the same error with Safari only. I tried the site on several other browsers and they had no problem.

Interestingly, in Chrome, it seems to automatically add the missing bracket when I view the source in the Dev Tools window.

Chrome Version: 67.0.3396.99 (Official Build) (64-bit)



来源:https://stackoverflow.com/questions/45108076/unclosed-square-bracket-doesnt-throw-error-in-jquery

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