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>

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');
盡管您可能想考慮為選擇器使用更簡單的屬性,而不是整個字符串化對象。
添加回答
舉報