【发布时间】:2013-12-03 13:42:42
【问题描述】:
首先 - 对于一般的混乱感到抱歉 - 每当我必须与 JS 打交道时,我都会感到不自在..
我有一个用于复制字段的小脚本,该脚本是从其他几个脚本中“窃取”的 - 但运行良好,没有任何问题..
问题是我想在一个页面上的多个实例上重用这个具有不同类名的脚本。
所以基本上,我需要传递一个参数以便稍后进行正则表达式(在代码中它被硬编码为"features" 但我需要作为变量"className")。
我的代码:
<script type="text/javascript">
jQuery(document).ready(function($) {
$.fn.addEle = function(e) {
// do not re-load anything
e.preventDefault();
// count elements to set new id and name-attributes
var num = $(e.target).parent().parent().find('p.feature-element').length;
// set the new id- and name-attributes integer
var newNum = parseInt(num) + parseInt(1);
// create our new form-fields
var newElem = $(e.target).parent().prev().clone();
// iterate over each input field
newElem.find('input').each(function(index) {
// find and replace ID in our clone with new id
var idRegExp = new RegExp( '(id_)(\\d+)' ,["i"]);
$(this).attr( 'id', $(this).attr('id').replace( idRegExp , "id_"+newNum ) );
// find and replace NAME in our clone with new name-id
var nameRegExp = new RegExp( '\\[features\\]\\[(\\d+)\\]' ,["i"]);
$(this).attr( 'name', $(this).attr('name').replace( nameRegExp , "[features]["+newNum+"]" ) );
// empty value
$(this).val('');
});
// add form-fields to the DOM
$( newElem ).insertBefore( $(e.target).parent() );
}
// add element on button click
$('.repeat-parent').live("click", function(e) { $.fn.addEle(e); });
});
</script>
现在,我是PHP 的人,尽管我尝试了很多,但从未真正正确地使用JS 语法。
所以简单地说 - 如何将参数传递给函数类型的函数(e),然后如何正则表达式参数(而不是字符串)?
总结-
- 第一个问题:
Q 向这样的函数添加参数的正确语法是什么?
据我了解,$.fn.addEle = function(e) 中的e 仅代表event。
那么我怎样才能添加一个参数,比如className,比如:
转这个:
$.fn.addEle = function(e){...}
$('.repeat-parent').live("click", function(e) { $.fn.addEle(e); });
进入这个:
$.fn.addEle = function(e,className){...}
$('.repeat-parent').live("click", function(e) { $.fn.addEle(e,className); });
在 PHP 中,我只需添加一个参数:
函数my_function() 到函数my_function($my_parameter='value'),然后调用my_function('my_new_value')
-
第二个问题是这些行中的正则表达式:
var nameRegExp = new RegExp( '\\[features\\]\\[(\\d+)\\]' ,["i"]);$(this).attr( 'name', $(this).attr('name').replace( nameRegExp , "[features]["+newNum+"]" ) );
如何把它变成这个,其中className实际上是一个参数而不是一个要搜索的字符串...
var nameRegExp = new RegExp( '\\["className"\\]\\[(\\d+)\\]' ,["i"]);
$(this).attr( 'name', $(this).attr('name').replace( nameRegExp , "['className']["+newNum+"]" ) );
(我想我也把所有的引号都弄错了,但是在正则表达式里面很混乱..)
【问题讨论】:
-
您的如何添加参数的示例不起作用吗?您遇到了什么错误?
-
我不完全确定 - 脚本绑定到一个按钮,当它失败时 - 按钮提交并转到另一个页面......我认为错误是:缺少(在参数列表之后。 (语法错误 - 指针在正则表达式中,我将变量放在正则表达式中..)
标签: javascript regex syntax parameters