我有以下字符串:
<a href="#" title="blahblah?foo=1&month={m{month}m}">bar</a>
所以我可以把标题作为字符串拉出来,但我想用{m {August} m}替换{m {month} m}并且它需要足够灵活,所以我也可以再用它替换它{M {九月} M}
我目前有这个:
var thetitle = $(this).attr('title');
var newtitle = thetitle.replace("{m{month}m}",months[currentmonth]);
第一次替换正常,但随后它删除了整个值并替换了&#34; {m {month} m}&#34;说&#34;八月&#34;,所以当我需要再次更换时,我无法定位它。
任何帮助都将不胜感激。
答案 0 :(得分:2)
尝试使用
var changeMonth = (function(){
var previous = 'month' ;
return function(title,month){
var temp = previous;
previous = month
return title.replace('m{' + temp + '}m', month);
}
})();
这对我有用。尝试
var changeMonth = (function(){
var previous = 'month' ;
return function(title,month){
var temp = previous;
previous = month;
return title.replace('m{' + temp + '}m','m{'+ month + '}m');
}
})();
var input = $('input');
var a = $('a');
$('button').on('click', function(){
var month = input.val();
var newMonth = changeMonth($(a).attr('title'), month);
$(a).attr('title', newMonth);
console.log($(a).attr('title'));
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" title="blahblah?foo=1&month={m{month}m}"></a>
Your month here<input type='text'>
<button>Change</button>
&#13;
答案 1 :(得分:1)
var title = "blahblah?foo=1&month={m{August}m}";
var previousmonth = "August";
var previousmonthstr = "{m{" + previousmonth + "}m}";
var currentmonth = "September";
var currentmonthstr = "{m{" + currentmonth + "}m}";
var newtitle = title.replace(previousmonthstr, currentmonthstr);
// Your title is stored in newtitle
查看实时演示here