gpt4 book ai didi

javascript - 将跨度转换为输入

转载 作者:数据小太阳 更新时间:2023-10-29 04:26:23 27 4
gpt4 key购买 nike

我正在开发网络应用程序,我有这样的要求,每当用户点击 span 内的 text 我需要将其convert输入字段模糊我需要将其转换回以再次跨越。所以我在我的一个 jsp 页面中使用了以下脚本。

Java 脚本:

<script type="text/javascript">
function covertSpan(id){

$('#'+id).click(function() {
var input = $("<input>", { val: $(this).text(),
type: "text" });
$(this).replaceWith(input);
input.select();
});

$('input').live('blur', function () {
var span=$("<span>", {text:$(this).val()});
$(this).replaceWith(span);

});
}

JSP 代码:

<span id="loadNumId" onmouseover="javascript:covertSpan(this.id);">5566</span>

现在我的问题是,只有第一次一切正常。我的意思是,每当我点击 span 内的文本 first time 时,它都会转换为输入字段,然后再次 onblur 它会从输入字段转换回普通文本。但是,如果再次尝试这样做,它将不起作用。上面的脚本有什么问题?

最佳答案

最好将您的 dom 结构更改为这样的结构(请注意,span 和输入并排并位于共享父 .inputSwitch

<div class="inputSwitch">
First Name: <span>John</span><input />
</div>
<div class="inputSwitch">
Last Name: <span>Doe</span><input />
</div>

然后我们可以像这样做我们的 JS,它将支持选择所有焦点和跳转到下一个/上一个跨度/输入:http://jsfiddle.net/x33gz6z9/

var $inputSwitches = $(".inputSwitch"),
$inputs = $inputSwitches.find("input"),
$spans = $inputSwitches.find("span");
$spans.on("click", function() {
var $this = $(this);
$this.hide().siblings("input").show().focus().select();
}).each( function() {
var $this = $(this);
$this.text($this.siblings("input").val());
});
$inputs.on("blur", function() {
var $this = $(this);
$this.hide().siblings("span").text($this.val()).show();
}).on('keydown', function(e) {
if (e.which == 9) {
e.preventDefault();
if (e.shiftKey) {
$(this).blur().parent().prevAll($inputSwitches).first().find($spans).click();
} else {
$(this).blur().parent().nextAll($inputSwitches).first().find($spans).click();
}
}
}).hide();

关于javascript - 将跨度转换为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374057/

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