繁体   English   中英

使用jQuery处理动态创建的表单元素而不会丢失其值

[英]manipulating dynamically created form elements without losing their values with jQuery

我想进行搜索并替换一些动态创建的表单。 这就像查找一个字符串的所有实例并将其替换为另一个字符串一样简单,由于每位格式只有11个实例并且仅构成各种属性的一部分而变得更加复杂。

我正在处理的事物的示例(这是我正在搜索和替换的“ 001”位):

<div id="step_title:001|title">
<label for="step_title:001|title|field">
<input id="step_title:001|title|field" name="step_title:001|title|field"/>

我以为这样的事情可以解决问题:

$(this).html($(this).html().replace('old string', 'new string'));

但是,由于表单的位是动态添加的,因此每次执行此操作时,表单数据都会丢失。 我尝试使用似乎保留数据的.clone()函数,但这不允许您操作该对象。 我也尝试执行搜索并直接替换到包含的对象上,但是我猜.replace()仅适用于字符串。

您可以只更新属性吗?

$('div, label, input').each(
    function() {
        var _this = $(this);
        _this.attr('id', _this.attr('id').replace('old string', 'new string'));
        _this.attr('for', _this.attr('id').replace('old string', 'new string'));
        _this.attr('name', _this.attr('id').replace('old string', 'new string'));
    }
);

可能会有点long ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM