JavaScript的;分隔符之间的REGEX并按空格分隔

时间:2017-09-26 10:46:21

标签: javascript jquery html

我有这段代码:

<!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(以空格分隔)。

我做错了什么?

1 个答案:

答案 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>

<强>样本

&#13;
&#13;
@TimeDate
&#13;
&#13;
&#13;