2017-09-11 17 views
0

タグ文字列にドットが含まれている場合はJquery。ハードコーディングされた場合、クエリは期待値を取得しますが、関数でタグを取得し連結した場合、クエリは失敗します。タグ名にドットを含むJquery要素

var tagWithDot = getTag(...) // tagWithDot === 'tag.withdot' 

console.log(tagWithDot === 'tag.withdot') // true 

console.log('#' + tagWithDot === '#tag.withdot') // true 

console.log('#' + tagWithDot.replace('.', '\\.') === '#tag\\.withdot') // true 

console.log($('#' + tagWithDot.replace('.', '\\.')) === $('#tag\\.withdot')) // false 

console.log($(('#' + tagWithDot.replace('.', '\\.'))) === $('#tag\\.withdot')) // false 
+0

[タグ名にドットを持つjQueryの要素を交換する場合でも、動作しませんの可能性のある重複「」 '\\。'](https://stackoverflow.com/questions/46162341/jquery-element-with-dot-in-tag-name-wont-work-even-if-replace-with) –

+0

何が ' ... getTag(...)で '?あなたの質問に疑問がありますか? –

+0

それはES9スーパースプレッドです:P – zer00ne

答えて

0

の代わりにあなたがreplace('.','\\.')を使用しjQuery's escapeSelector

var tagWithDot = "#tag.withdot"; 
 

 
console.log($.escapeSelector(tagWithDot));
<script src="//code.jquery.com/jquery-3.1.0.js"></script>

0

を使用することができます\\.のものを使用して手動で.を置き換えるここで働いているようです。

$.escapeSelectorを使用する場合は、#や#もエスケープしないようにしてください。あなたが望むものではない可能性があります。

var tagWithDot = "#tagwith.dot"; 
 

 
setTimeout(function() { 
 
    $(tagWithDot.replace('.','\\.')).text('Replaced'); 
 
}, 2000);
<script src="//code.jquery.com/jquery-3.1.0.js"></script> 
 

 
<div>Wait 2 seconds and replace text in div with id #tagwith.dot<div> 
 
<br> 
 
<div id="tagwith.dot">This should get replaced</div>

関連する問題