如何使用 jquery 将 HTML 输入控件替换为其值?
How to replace a HTML input control with its Value using jquery?
我使用以下代码在变量中有 HTML。
var htmlTables = '<div><table><tr><td><input id="txtweek2" name="txtweek2" style="width:100px" class="form-control timebox" value=""></td>
<td><input id="txtweek3" name="txtweek3" style="width:100px" class="form-control timebox" value="test value"></td></tr></table></div>';
现在我需要用它的值替换输入控件,我需要如下输出。
var htmlTables = '<div><table><tr><td></td>
<td>test value</td></tr></table></div>';
我尝试使用以下代码。
$(htmlTables).find('input').each(function () {
alert(this.value);
this.replaceWith(this.value);
//$(this).replaceWith("test");
请让我知道可能性。我提供的 HTML 只是一个示例。我在 html 字符串中有更多 div、table、tr、td、center 等。
谢谢。
如果您在 htmlTables 变量中输出代码,则可以使用 jQuery 使用以下代码将输入字段替换为它们的值:
jQuery('#txtweek2').replaceWith(jQuery('#txtweek2').val());
jQuery('#txtweek3').replaceWith(jQuery('#txtweek3').val());
你可以在这里玩:
https://jsfiddle.net/cckumk8o/
如果您不知道 id 并且内容是动态生成的,您可以使用 class 替换元素,如下所示:
var count=jQuery('.timebox').size();
for (i = 0; i < count; i++) {
jQuery('input.timebox:eq(0)').replaceWith(jQuery('input.timebox:eq(0)').val());
}
也可以在这里找到:
https://jsfiddle.net/y1qemn5b/
我使用以下代码在变量中有 HTML。
var htmlTables = '<div><table><tr><td><input id="txtweek2" name="txtweek2" style="width:100px" class="form-control timebox" value=""></td>
<td><input id="txtweek3" name="txtweek3" style="width:100px" class="form-control timebox" value="test value"></td></tr></table></div>';
现在我需要用它的值替换输入控件,我需要如下输出。
var htmlTables = '<div><table><tr><td></td>
<td>test value</td></tr></table></div>';
我尝试使用以下代码。
$(htmlTables).find('input').each(function () {
alert(this.value);
this.replaceWith(this.value);
//$(this).replaceWith("test");
请让我知道可能性。我提供的 HTML 只是一个示例。我在 html 字符串中有更多 div、table、tr、td、center 等。
谢谢。
如果您在 htmlTables 变量中输出代码,则可以使用 jQuery 使用以下代码将输入字段替换为它们的值:
jQuery('#txtweek2').replaceWith(jQuery('#txtweek2').val());
jQuery('#txtweek3').replaceWith(jQuery('#txtweek3').val());
你可以在这里玩:
https://jsfiddle.net/cckumk8o/
如果您不知道 id 并且内容是动态生成的,您可以使用 class 替换元素,如下所示:
var count=jQuery('.timebox').size();
for (i = 0; i < count; i++) {
jQuery('input.timebox:eq(0)').replaceWith(jQuery('input.timebox:eq(0)').val());
}
也可以在这里找到: https://jsfiddle.net/y1qemn5b/