我有这段代码:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
window.onload = function() {
var e = document.getElementById("first"), n=document.getElementById("second");
e.addEventListener("input", function() {
n.value = e.value.match( /\<span class="my_class">(.+)\<\/span>/ )[1]
})
};
</script>
</head>
<body>
<input class="textfield" id="first"><br><br>
<input class="textfield" id="second">
</body>
</html>
当您在<span class="my_class">test</span>
字段中插入first
时,second
字段将输出test
。这正是我想要的。
但如果我插入例如<span class="my_class">test</span> some text<span class="my_class">hello</span>
我收到了test</span> some text<span class="my_class">hello
而不是test hello
(以空格分隔)。
我做错了什么?
答案 0 :(得分:2)
使用span
构造来解析HTML并获取标记内的值<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
var e = document.getElementById("first"),
n = document.getElementById("second");
e.addEventListener("input", function() {
var valueArr = [];
$(e.value).each(function(v, i) {
if (i.nodeName == "SPAN" && i.classList.contains( "my_class" ) ) {
valueArr.push($(i).text());
}
});
n.value = valueArr.join(" ");
})
};
</script>
</head>
<body>
<input class="textfield" id="first"><br><br>
<input class="textfield" id="second">
</body>
</html>
<强>样本强>
@TimeDate
&#13;