[英]Find and replace a number using Javascript
我有一段HTML,它会一遍又一遍地使用jQuery重复(当用户单击“添加”时,它会创建另一个块:
<p>
<label for="question[1][text]">Question: <span class="req">*</span></label>
<input name="question[1][text]" id="A_Question_1" value="" type="text" class="f_input" />
</p>
<p>
<label for="question[1][type]">Type: <span class="req">*</span></label>
<input name="question[1][type]" id="A_Type_1" type="text" class="f_input" />
</p>
对于该块的每次迭代,我需要将每个数字加1,以便下一个块自动创建:
<p>
<label for="question[2][text]">Question: <span class="req">*</span></label>
<input name="question[2][text]" id="A_Question_1" value="" type="text" class="f_input" />
</p>
<p>
<label for="question[2][type]">Type: <span class="req">*</span></label>
<input name="question[2][type]" id="A_Type_1" type="text" class="f_input" />
</p>
我敢肯定它很简单,但是我对Regexs等没有足够的经验,无法解决该问题。 谢谢 :)
JQote为JQuery提供了HTML模板库。 它由包含其参数的对象调用。
<script type="text/html" id="template">
<![CDATA[
<p>
<label for="question[<%= this.iteration %>][text]">Question: <span class="req">*</span></label>
<input name="question[<%= this.iteration %>][text]" id="A_Question_<%= this.iteration %>" value="" type="text" class="f_input" />
</p>
<p>
<label for="question[<%= this.iteration %>][type]">Type: <span class="req">*</span></label>
<input name="question[<%= this.iteration %>][type]" id="A_Type_<%= this.iteration %>" type="text" class="f_input" />
</p>
]]>
</script>
然后作为add()
函数的一部分:
<script type="text/javascript">
var globalIteration = 0
function add() {
<...your code...>
globalIteration++;
var obj= {
iteration: globalIteration,
<...any other variables to insert into template...>
};
$('#template').jqote(obj).appendTo($('body'));
}
</script>
您可以将模板存储在带有ID占位符的某些隐藏div中(例如#id#
)。
然后,您可以使用javascript中的实际ID替换占位符。 就像是
var html = $('#template').html().replace('#id#', id);
list.append(html);
下一个ID可以根据当前的孩子数量来计算。
var id = list.children().length + 1;
这样的事情应该起作用:
$(document).ready(function() {
$container = $('#container');
$button = $('#button')
.data('clicked', 0)
.click(function() {
var clicked = $button.data('clicked');
$container.append('<p><label for="question[' + clicked + '][text]">Question: <span class="req">*</span></label><input name="question[' + clicked + '][text]" id="A_Question_' + clicked + '" value="" type="text" class="f_input" /></p>');
$button.data('clicked', clicked + 1);
});
});
这取决于您如何绑定功能。 如果您在javascript中进行绑定,则可能会将数字用作添加链接的假属性。
就像是
'<a href="javascript:;" question_number="1">Add</a>
在您的JavaScript中将[1]替换为$(this).attr('question_number'),最后添加$(this).attr('question_number',nextId)
更好的解决方案可能是将其附加到链接的ID上,并在JavaScript完成时更改ID,但是如果您按ID进行绑定,则不是一个好的解决方案。
如果您要使用类似以下内容的方法直接在HTML中绑定onclick
<a href="javascript:;" onclick="my_func();">Add</a/>
修改您的函数以采用参数,并在javascript的末尾更改参数,类似于上述。 我也喜欢安迪的解决方案。
这是我的操作方法http://pintum.com.au/goCruising/details.html#tabs-2单击添加按钮。
它使用jQuery,jtemplates插件和JSON。 只需查看源代码以了解其工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.