gpt4 book ai didi

javascript - jquery/JS 动态控件的简单数据绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 04:50:01 24 4
gpt4 key购买 nike

我在 html 页面上有一个 和 元素,通过 js 动态创建。

<input type="text" id="MyInput" name="MyInput" 
class='form-control copyMe' placeholder="enter smth pls"/>
<div id="jsonTextAreaDiv" contenteditable="true">
<span id="MyInput_JSON"></span>
</div>

我想要从输入到跨度的文本绑定(bind)。

所以,我选择下一个 JS:

$(document).on('input', 'input.copyMe', function(){
var valToInsert = $(this).val();
var idToInsert = $(this).attr("id") + "_JSON";
document.getElementById(idToInsert).innerHTML = valToInsert;
});

可能全部都在一行 jquery 中,但是......无论如何。在输入要输入的文本期间,此绑定(bind)工作正常。但是一旦输入失去焦点 - 突然跨度失去内部文本。我不知道为什么。这正是我的问题,这是怎么发生的?

我已经通过添加“解决”了这个问题

 $(document).on('input', 'input.copyMe', function(){
var valToInsert = $(this).val();
var idToInsert = $(this).attr("id") + "_JSON";
document.getElementById(idToInsert).innerHTML=valToInsert;
}).on('blur', '.copyMe', function(){
var valToInsert = $(this).val();
var idToInsert = $(this).attr("id") + "_JSON";
document.getElementById(idToInsert).innerHTML=valToInsert;});

这样它就可以像我想要的那样工作。但这是荒谬的。关于为什么值首先从跨度中消失的任何想法?

提前致谢。

最佳答案

更改您的 input 事件以使用 change 事件。 IE 不正确支持“输入”事件。或者,您可以尝试使用 keyup 事件。

$(document).on('change', 'input.copyMe', function(){
var valToInsert = $(this).val();
var idToInsert = "#" + $(this).attr("id") + "_JSON";
$(idToInsert).html(valToInsert);
});

另外,我也将你的最后一行更改为 jQuery。没有理由将 jQuery 和纯 JS 混合在一起。如果保持统一,它会更容易阅读。

关于javascript - jquery/JS 动态控件的简单数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42699250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com