开发者

jquery: replace inputs with spans

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('<spa开发者_运维知识库n></span>') // this effectively creates: <span></span><input value=____>

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?


For the updated question:

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();
});

You can view a more detailed demo here, with per-row edit toggling.


For the original question:

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

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

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

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));
});​

You can try a demo here


Seems to me like the easiest solution would be to change the inputs to readonly and remove the border (and possibly change background color, depending on your UI), which essentially makes them appear as a regular <span> label.

function spanify() {
  $('#container input')
    .attr("readonly", "readonly")
    .css("borderWidth", "0");
}

function despanify() {
  $('#container input')
    .removeAttr("readonly")
    .css("borderWidth", "auto");
}

Is that feasible?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜