我有以下 jQuery 代码:
$.each($(".coin"), function() {
var content = "/*:before content*/";
$("input", this).val(content);
});
我想根据其伪元素的 content
属性值 (.coin:before
) 使用 jQuery 更改每个输入元素的值。
最佳答案
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.
因此您可以使用以下命令获取伪元素的 content
值:
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>
关于javascript - 使用 JavaScript 检索伪元素的内容属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34122243/