我有以下jQuery代码:
$.each($(".coin"), function() {
var content = "/*:before content*/";
$("input", this).val(content);
});
我想基于其伪元素的内容属性值(.coin:before)使用jQuery更改每个输入元素的值.
这是一个例子:http://jsfiddle.net/aledroner/s2mgd1mo/2/
最佳答案
According to MDN,到
.getComputedStyle()
method的第二个参数是伪元素:
var style = window.getComputedStyle(element[, pseudoElt]);
pseudoElt (Optional) – A string specifying the pseudo-element to match. Must be omitted (or null) for regular elements.
因此,您可以使用以下内容来获取伪元素的内容值:
window.getComputedStyle(this, ':before').content;
$('.coin').each(function() {
var content = window.getComputedStyle(this, ':before').content;
$("input", this).val(content);
});
如果要根据角色获取实体代码,还可以使用以下内容:
function getEntityFromCharacter(character) {
var hexCode = character.replace(/['"]/g, '').charCodeAt(0).toString(16).toUpperCase();
while (hexCode.length < 4) {
hexCode = '0' + hexCode;
}
return '\\' + hexCode + ';';
}
$('.coin').each(function() {
var content = window.getComputedStyle(this, ':before').content;
$('input', this).val(getEntityFromCharacter(content));
});
.dollar:before {
content: '\0024'
}
.yen:before {
content: '\00A5'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="coin dollar">
<input type="text" />
</div>
<div class="coin yen">
<input type="text" />
</div>