2016-12-14 8 views
0

エラー:構文エラー、認識できない表現私はコンソールログに次のようだまで、私のonclickイベントをトリガしようとしていた

$("li[data-path='00\'s']").on("click", function() 
{ 
    console.log("in 00s"); 
    $('#replacewithimg').replaceWith('<img id="replacewithimg" src="../assets/img/playlist-icons/00s.png" style="padding-left: 5px;padding-right: 10px;padding-bottom: 5px;">'); 
    $('#replacewithtext').replaceWith('<b id="replacewithtext" style="font-size:30px;">00\'s Playlist</b>'); 
    $('#replacewithtext2').replaceWith('<p id="replacewithtext2" style="font-size:18px; padding-top:10px;">Includes Amy Whinehouse, Westlife, The Killers...</p>'); 
}); 

をクリックすると次のように

Error: Syntax error, unrecognized expression: li[data-path='00's']

私のコードですデータパスが含まれているliタグに一致する要素に

00's

もの。問題はエスケープする一重引用符であると思いますか?

答えて

3

使用

$("li[data-path='00\\'s']") 

代わりの

$("li[data-path='00\'s']") 

機能するために、今、残りのバックスラッシュは、CSSセレクタ

のためにCSSが使用することを送信する関数呼び出しの第二のバックスラッシュをエスケープする最初のバックスラッシュ

PS:これを避けるために代わりに使用してください。'

$('#replacewithtext').replaceWith("<b id='replacewithtext' style='font-size:30px;'>00\'s Playlist</b>"); 

DEMO

$("li[data-path='00\\'s']").on("click", function() 
 
{ 
 
    console.log("in 00s"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<li data-path="00's" 
 
    >Click</li>

+0

ありがとう!残念ながら、それはコンソールのエラーを修正しますが、要素をクリックすると修正されます。関数を入力しないでください? – irishwill200

+1

@ irishwill200私はデモを追加して、それが実際に機能に入っていることを示しています。今問題は他のどこかにあるはずです。エラーを見つけて、つかまった場合に再度質問してください:) – bugwheels94

+0

@ irishwill200は、ページがレンダリングされた後にコードによって生成された 'li'です/' .on'コードが(例えばajax呼び出しを介して)呼び出されましたか? –

0

ここでは、おそらく最善の策は、あなたが\を使用して好きではない場合は、変数を使用することで、いくつかのバリエーションです:

// with outer ', inner ", single \ 
 
console.log($('div[data-path="00\'s"]').length) 
 
// with outer ", inner ', double \\ 
 
console.log($("div[data-path='00\\'s']").length) 
 

 
// No \, using a variable, with outer ' and inner " 
 
// This doesn't work inline as the js parser sees the ' 
 
// rather than it being a jquery limitation 
 
var path = "00's" 
 
console.log($('div[data-path="' + path + '"]').length) 
 

 
// without inner " or ' 
 

 
// With outer " use double \\ 
 
console.log($("div[data-path=00\\'s]").length) 
 
// With outer ' use triple \\\ 
 
console.log($('div[data-path=00\\\'s]').length) 
 

 
// doesn't work 
 
// console.log($("div[data-path=00's]").length) 
 
// console.log($("div[data-path=00\'s]").length)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div data-path="00's"> 
 
</div>

関連する問題