javascript 将跨度转换为输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16374057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:22:25  来源:igfitidea点击:

Converting Span to Input

javascriptjqueryjspweb-applications

提问by Kishan_KP

I am developing web app, I have such a requirement that whenever user click on textinside spani need convertit into input fieldand on bluri need to convert it backto span again. So i am using following script in one of my jsp page.

我正在开发网络应用程序,我有这样一个要求,每当用户点击text里面时,span我需要convert它进入input fieldon blur我需要convert it back再次跨越。所以我在我的一个 jsp 页面中使用了以下脚本。

Java Script:

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 Code:

JSP代码:

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

Now my problem is, everything works fine only for the first time. I mean whenever i click on the text inside span for the first timeit converts into input field and again onblurit coverts back from input field to normal text. But if try once again to do so it won't work. Whats wrong with above script?

现在我的问题是,只有第一次一切正常。我的意思是每当我点击跨度内的文本时,first time它会转换为输入字段,然后再次onblur从输入字段转换回普通文本。但如果再试一次,它就行不通了。上面的脚本有什么问题?

回答by Dallas

Would be good to change your dom structure to something like this (note that the span and the input are side by side and within a shared parent .inputSwitch

将您的 dom 结构更改为这样的内容会很好(请注意,跨度和输入并排并在共享父级内 .inputSwitch

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

Then we can do our JS like this, it will support selecting all on focus and tabbing to get to the next/previous span/input: http://jsfiddle.net/x33gz6z9/

然后我们可以像这样做我们的 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();

回答by Justin Niessner

First, you need to change your click handler to use live()as well. You should take note, though, that live()has been deprecated for quite a while now. You should be using on()in both cases instead.

首先,您还需要更改要使用的点击处理程序live()。不过,您应该注意,它live()已经被弃用了很长时间。您应该on()在这两种情况下都使用。

Secondly, when you replace the input with the span, you don't give the element an id. Therefore, the element no longer matches the selector for your click handler.

其次,当你用跨度替换输入时,你没有给元素一个 id。因此,该元素不再匹配您的点击处理程序的选择器。

Personally, I would take a different (and simpler) approach completely. I would have both the span and in the input in my markup side by side. One would be hidden while the other is shown. This would give you less chance to make mistakes when trying to recreate DOM elements and improve performance since you won't constantly be adding/removing elements from the DOM.

就个人而言,我会完全采用不同(且更简单)的方法。我会在我的标记中并排放置跨度和输入。一个将被隐藏,而另一个显示。这将使您在尝试重新创建 DOM 元素和提高性能时犯错的机会减少,因为您不会经常从 DOM 中添加/删除元素。

回答by Anders Lindén

I understand you think that element replacement is a nice thing, however, I would use a prompt to get the text. Why? It is a lot easier and actually a bit prettier for the user as well. If you are curious on how to do it, I show you.

我知道您认为元素替换是一件好事,但是,我会使用提示来获取文本。为什么?这对用户来说要容易得多,实际上也更漂亮一些。如果你对如何做感到好奇,我会告诉你。

html:

html:

<span class='editable'>foobar</span>

js:

js:

$(function()
{
  $('span.editable').click(function()
  {
    var span = $(this);
    var text = span.text();

    var new_text = prompt("Change value", text);

    if (new_text != null)
      span.text(new_text);
  });
});

http://jsfiddle.net/qJxhV/1/

http://jsfiddle.net/qJxhV/1/

回答by Zachary Blackwood

A more generic version of smerny's excellent answerwith id's can be made by slightly altering two lines: $input.attr("ID", "loadNum");becomes $input.attr("ID", $(this).attr("ID"));-- this way, it simply takes the current id, and keeps it, whatever it is.

可以通过稍微更改以下两行来制作smerny 对id的出色回答的更通用版本: $input.attr("ID", "loadNum");变成$input.attr("ID", $(this).attr("ID"));- 这样,它只需要当前的 id,并保留它,无论它是什么。

Similarly, $span.attr("ID", "loadNum");becomes $span.attr("ID", $(this).attr("ID"));

类似地, $span.attr("ID", "loadNum");变成$span.attr("ID", $(this).attr("ID"));

This simply allows the functions to be applied to any div. With two similar lines added, both id and class work fine. See example.

这只是允许将函数应用于任何 div。添加了两个类似的行后,id 和 class 都可以正常工作。参见示例

回答by Sahil Thukral

I have done little change in code, By using this input type cant be blank, it will back to its real value.

我对代码做了一点改动,通过使用这个输入类型不能为空,它会恢复到它的真实值。

 var switchToInput = function () {
        var $input = $("<input>", {
            val: $(this).text(),
            type: "text",
            rel : jQuery(this).text(),
        });
        $input.addClass("loadNum");
        $(this).replaceWith($input);
        $input.on("blur", switchToSpan);
        $input.select();
    };
    var switchToSpan = function () {
            if(jQuery(this).val()){
                        var $text = jQuery(this).val();
                } else {
                      var $text = jQuery(this).attr('rel');
                }
        var $span = $("<span>", {
            text: $text,
        });
        $span.addClass("loadNum");
        $(this).replaceWith($span);
        $span.on("click", switchToInput);
    }
    $(".loadNum").on("click", switchToInput);

jsFiddle:- https://jsfiddle.net/svsp3wqL/

jsFiddle:- https://jsfiddle.net/svsp3wqL/