jQuery:用范围替换输入 [英] jquery: replace inputs with spans

查看:56
本文介绍了jQuery:用范围替换输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用包含输入值的跨度替换输入,以便能够在单击按钮时将其切换回原来的状态.我认为这很容易分两个阶段完成-在输入前面添加<span>[input value]</span>,然后隐藏输入.唯一的问题是我在第一部分遇到麻烦.我正在尝试

I'm trying to replace inputs with spans containing the input values in such a way as to be able to switch them back upon clicking a button. I figure this would be most easily done in two stages - adding <span>[input value]</span> in front of the inputs, and then hiding the inputs. The only problem is I'm having trouble with the first part. I'm trying things like

$('#container').find('input')
    .parent()
    .prepend('<span></span>') // this effectively creates: <span></span><input value=____>

但是,在前置语句$(this)内似乎是未定义的,所以我不能这样做

However, inside the prepend statement $(this) seems to be undefined, so I can't do

    .prepend('<span>'+$(this).children('input').val()+'</span>')

由于有多个输入,因此我不能简单地将输入值放入变量中.我该怎么办?

Since there are several inputs, I can't simply put the input value into a variable. How would I do this?

推荐答案

有关更新的问题:

您可以执行以下操作(以注释为基础,每行进行一次编辑):

You can do something like this (basing this on comments, an edit per row):

$('input', context).each(function() {
  $("<span />", { text: this.value, "class":"view" }).insertAfter(this);
  $(this).hide();
});

您可以在此处查看更详细的演示,并可以按行切换切换.

对于原始问题:

您将为此使用 .replaceWith() :

You'll want to use .replaceWith() for this:

$('#container').find('input').each(function() {
  $(this).replaceWith("<span>" + this.value + "</span>");
});

.each() 创建一个闭包,其中this引用输入元素,因此您可以使用this.value例如.

The .each() creates a closure in which this refers to the input element, so you can use this.value for example.

要确保已处理编码,请对其进行扩展以使用 .text() ,像这样:

To make sure encoding is taken care of, expand it a bit to use .text(), like this:

$('#container').find('input').each(function() {
  $(this).replaceWith($("<span />").text(this.value));
});​

您可以在此处尝试演示

这篇关于jQuery:用范围替换输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆