我有以下表格
<form action="http://www.domain.com/processing.php?page=first§ion=77&userid=replaceme">
如何使用 jquery 我可以用 jquery 变量更新“replaceme”?
我有以下表格
<form action="http://www.domain.com/processing.php?page=first§ion=77&userid=replaceme">
如何使用 jquery 我可以用 jquery 变量更新“replaceme”?
我认为您应该使用正则表达式并匹配“userid”参数的名称,而不是“replaceme”值。
尝试:
var $form = $('form');
$form.prop('action', $form.prop('action').replace(/([\?&])(userid=)[^&#]*/, '$1$2' + newValue));
在哪里newValue
保存你想要的东西来代替“replaceme”的变量。
注意:在您的 html 中,URL 中的“&”字符应替换为字符 entity &
。
更新:
使用@undefined 的建议,这将是:
$('form').prop('action', function(i, action){ return action.replace(/([\?&])(userid=)[^&#]*/, '$1$2' + newValue); });
现在不需要$form
变量了。
这是一个jsfiddle 演示,显示了以下情况:
正则表达式的解释:
$1
匹配一个“?” 或者 '&'。$2
匹配'userid='。首先添加一个ID:
<form id="myForm" action="http://www.domain.com/processing.php?page=first§ion=77&userid=replaceme">
然后在 DOM 上准备好:
$(function() {
var $form = $('#myForm');
var someVar = 'foo';
$form.attr('action', $form.attr('action').replace('replaceme', someVar));
});
演示:http: //jsfiddle.net/HBQcx/
假设您有以下标记:
<form id="testform" action="http://www.domain.com/processing.php?page=first§ion=77&userid=replaceme">
</form>
并且您想更改action
属性中的一些文本::
action = $('#testform').attr('action');//get the action attribute.
console.log(action);
action = action.replace('replaceme','changed');//change the action text.
$('#testform').attr('action',action);//change the action attribute.
console.log($('#testform').attr('action'));//test the results.