我想将每个字符包装到a中,<span></span>
并希望输出为<span>a</span><span>b</span><span>c</span>
。
我尝试了以下操作,但没有帮助。
<div contenteditable="true" id="text1" type="text" placeholder="type something...">
$(function() {
$("#text1").keyup(function(event) {
$(this).wrapInner( "<span class='test'></span>" )
});
});
输出以下内容;这不是我所需要的。有什么帮助吗?
<span class="test">
<span class="test">
<span class="test">
<span class="test">ffdf</span>
</span>
</span>
</span>
这是我的解决方案。code
输入div下方有一个标签,用于控制div的内容:
txt = $("#text1").html();
$("#out").text(txt);
$(function() {
$("#text1").keyup(function(event) {
txt = txt + "<span class='test'>"+String.fromCharCode(event.which)+"</span>";
$(this).html(txt);
$("#out").text($(this).html());
});
});
#text1 {
border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" id="text1" type="text" placeholder="type something..."></div>
<code id="out"></code>
替换char的纯函数如下所示:
txt = $("#text1").html();
$(function() {
$("#text1").keyup(function(event) {
txt += "<span>" + String.fromCharCode(event.which) + "</span>";
$(this).html(txt);
});
});
这是另一个与区分大小写的funckeypress
一起使用preventDefault()
以防止出现多余字符的函数:
txt = $("#text1").html();
$(function() {
$("#text1").keypress(function(event) {
txt += "<span>" + String.fromCharCode(event.which) + "</span>";
event.preventDefault();
$(this).html(txt);
$("#out").text(txt);
});
});
#text1 {
border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" id="text1" type="text" placeholder="type something..."></div>
<code id="out"></code>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句