You need to enclose special characters in quotes when using a attribute based selector.
if ($('ul li a[href="' + id + '"]').length) {
Your version of selector would result
if ($("ul li a[href=#!...]").length) {
The #!
will throw unrecognized expression.
My version where the ""
escape the characters
if ($('ul li a[href="#!..."]').length) {
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…