亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用帶雙引號的數據值屬性的 jQuery 選擇器

使用帶雙引號的數據值屬性的 jQuery 選擇器

幕布斯6054654 2023-03-24 17:00:34
我正在學習 UI 自動化測試,我一直在嘗試定位這個元素<a tabindex="-1" href="javascript:void(0)" data-value="{"stringVal":"date-desc-rank"}" id="s-result-sort-select_4" class="a-dropdown-link">Release Date</a>在網頁上使用其“數據值”屬性。但是當我運行以下命令時:$('a[data-value="{"stringVal":"date-desc-rank"}"]')它返回一個錯誤:未捕獲的 DOMException:Document.querySelector:'a[data-value="{"stringVal":"date-desc-rank"}"]' 不是有效的選擇器我還嘗試用反斜杠符號轉義雙引號,但沒有結果。任何幫助將不勝感激。
查看完整描述

2 回答

?
慕后森

TA貢獻1802條經驗 獲得超5個贊

您需要在 html 中使用單引號來包裝 json 并在 jQuery 選擇器中使用轉義引號。


另一種方法是使用$('a[data-value]').filter(function)并檢查回調中的數據。當數據屬性包含有效的 json 時,jQuerydata()會自動為您將其解析為對象/數組。


// this version changes the text

$('a[data-value=\'{"stringVal":"date-desc-rank"}\']').text('Inserted text');


// this version changes the color

$('a[data-value]').filter(function(){  

   return $(this).data('value').stringVal === "date-desc-rank"

}).css('color', 'red');

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a tabindex="-1" href="javascript:void(0)" data-value='{"stringVal":"date-desc-rank"}' id="s-result-sort-select_4" class="a-dropdown-link">Release Date</a>


查看完整回答
反對 回復 2023-03-24
?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

當我想將它存儲在中時,我使用encodeURIComponent來編碼data-

我有一些關于 String 對象的原型來簡化這個過程。

String.prototype.encode = function() { return encodeURIComponent(this).replace(/'/g,'%27');};

String.prototype.decode = function() { return decodeURIComponent(this); };


`{"stringVal":"date-desc-rank"}`.encode(); //%7B%22stringVal%22%3A%22date-desc-rank%22%7D


<a data-value="%7B%22stringVal%22%3A%22date-desc-rank%22%7D">Release Date</a>

此處另一個答案的旁注,您也可以在選擇器中使用屬性,無需過濾。


$(`a[data-value="%7B%22stringVal%22%3A%22date-desc-rank%22%7D"]`).css('color', 'red');

盡管您可能想考慮為選擇器使用更簡單的屬性,而不是整個字符串化對象。


查看完整回答
反對 回復 2023-03-24
  • 2 回答
  • 0 關注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號