0

我还有另一个难题需要用 JavaScript 解决。字符串变量来自外部表单输入值,如下所示

document.addEventListener('DOMContentLoaded', function() {
var Country = document.getElementById('countr').value;
}, false);

我需要更改的字符串地址是相对 href 地址的一部分,将采用两种不同的形式。

模型/世界/some_site.html

或者

模型/本地/some_site.html

变量 Country 也会发生变化,例如:German、England、France 等。

如果我想用 Country 变量替换“世界”或“本地”,我需要做的就是做类似的事情

var address = address.split('world').join(Country).split('local').join(Country);

或者

var address = address.replace('world', new RegExp(Country, 'g')).replace('local', new RegExp(Country, 'g'));

结果应该是这样的

模型/德语/some_site.html

但它不起作用我不知道为什么。任何帮助对我来说都是非常宝贵的。

我发现我的 Country 变量不想被处理,为什么?该脚本根本不显示我的变量。

document.addEventListener('DOMContentLoaded', function() {
var Country = document.getElementById('cotr').value;
}, false);

document.write(Country);

所以这个例子也不能正常工作

address.replace(/(local|world)/,Country)

有什么帮助吗?

我的真实代码如下所示

Indeks.prototype.wyswietl = function(adres)
{
if (typeof adres == 'undefined') adres = 
document.forms[this.id].elements['hasla'].value;
if (typeof this.ramka == 'string')
{
var okno = 
window.open(adres, this.ramka, 'menubar=yes,toolbar=yes,location=yes,directories=no,status=yes,scrollbars=yes,resizable=yes');
if (okno) okno.focus();
else window.location.href = adres;
}
else this.ramka.location.href = 
adres.replace(/(world|local)/,Country);//here I need replacement adres is address
}
4

2 回答 2

1

models/local/some_site.html你想用国家变量替换文本的中间部分。

您可以使用split()函数根据/. 获得拆分后的字符串后,您可以获取index[1]值,因为它包含国家/地区值localworld要替换。
然后你可以使用replace()函数来替换文本。

示例代码如下:

    <script language="javascript">
    var address="models/local/some_site.html";
    var Country="france";//Example
    var finaladdress=address.replace(address.split("/")[1],Country);    
    </script>

完整的解决方案:

Code1:将您的Country变量声明为global

var Country;//declare the Country outside the function so it becomes global
document.addEventListener('DOMContentLoaded', function() {
Country = document.getElementById('countr').value;
}, false);

Code2:replacement在这里做

Indeks.prototype.wyswietl = function(adres)
{
if (typeof adres == 'undefined') adres = 
document.forms[this.id].elements['hasla'].value;
if (typeof this.ramka == 'string')
{
var okno = 
window.open(adres, this.ramka, 'menubar=yes,toolbar=yes,location=yes,directories=no,status=yes,scrollbars=yes,resizable=yes');
if (okno) okno.focus();
else window.location.href = adres;
}
else this.ramka.location.href = 
adres.replace(adres.split("/")[1]),document.getElementById('countr').value); // here I need replacement
}
于 2013-11-11T08:40:20.367 回答
1

首先,join()用于数组并在结果字符串中留下逗号,因此您应该使用它concat()。其次,replace()将是一个更简单的解决方案,如下所示:

var regex = /(world|local)/;
address.replace(regex,Country);

编辑:

我已经测试了我的代码,所以该方法本身有效。这种情况下的问题必须在您的Country变量中。你确定它的范围是全球性的吗?它在您的函数中出现的方式表明它在事件侦听器之外的任何地方都不可见。或者,如果您认为全局变量是邪恶的,也许您可​​以将事件侦听器直接链接到代码的其余部分并将其作为函数参数传递。

于 2013-11-11T08:49:18.500 回答