【问题标题】:Trying to dynamically replace a url &option value based on <input> button尝试基于 <input> 按钮动态替换 url &option 值
【发布时间】:2018-11-06 10:41:45
【问题描述】:

我正在尝试动态替换 url 值,我正在使用替换,因为我不希望在每次点击时重复该值

我当然不是世界上最好的程序员,而且我不确定我的语法是否有效。

我试图在下面完成的一般想法是页面上有几个 url,在任何给定时间只显示一个我使用滑块以无缝方式隐藏/显示每个 url。

我想将位置传递给 javascript 函数(它将是一个数字),该函数应该获取位置编号并替换页面上所有 href="" 中的部分。

但我似乎无法让它工作。

function getlocation(loc) {
  $('a').each(function() {
    var location = $(this).attr('href');
    $(this).attr('href').replace("&location=100", "&location=loc");
    console.log('error');
  });
}
<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>

<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>


<feildset>
  <input id="mtl" name="location" type="radio" checked>
  <label for="mtl" onclick="getlocation(mtl)">Montreal</label>
  <br>
  <br>
  <input id="frkfrt" name="location" type="radio" onclick="">
  <label for="frkfrt" onclick="getlocation(frkfrt)">Frankfurt</label>



</feildset>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

【问题讨论】:

  • feildset 拼写在编程中很重要。
  • 是的,我打错了标签,但 javascript 仍然没有产生预期的结果。

标签: javascript jquery html replace href


【解决方案1】:
  • frkfrt 和 mtl 不是变量 - 您希望将其作为 字符串 传递。但内联事件处理程序与 HTML 中的 eval 一样糟糕 - 改为使用 Javascript 正确附加处理程序,以降低此类问题的可能性。
  • replace 不会改变原始字符串 - 字符串是不可变的。相反,您需要显式分配hrefs 才能更改它们。
  • getlocation 中,您必须连接 loc 变量与&amp;location=

['mtl', 'frkfrt'].forEach(loc => {
  document.querySelector(`[for="${loc}"]`).onclick = () => getlocation(loc);
});


function getlocation(loc) {
  document.querySelectorAll('a').forEach(a => {
    a.href = a.href.replace(/&location=.*$/, "&location=" + loc);
  });
}
<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>

<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>


<feildset>
  <input id="mtl" name="location" type="radio" checked>
  <label for="mtl">Montreal</label>
  <br>
  <br>
  <input id="frkfrt" name="location" type="radio">
  <label for="frkfrt">Frankfurt</label>



</feildset>

【讨论】:

  • 啊,我明白了,是否可以将正则表达式模式应用于替换 a.href = a.href.replace("&location=100", "&location=" + loc);这样如果 &location=#### 任何数字都会被替换?
  • 如果要使用正则表达式,可以从location匹配到字符串的末尾
  • 好吧,我正在解决它我试过 a.href = a.href.replace("&location=/[[0-9]+]/", "&location=" + loc);我怀疑使用标准正则表达式模式不起作用需要转义
  • 只需运行 sn-p。你定义并使用一个正则表达式已经在一个字符串中像这样
【解决方案2】:

如果我很了解您的需求,请尝试替换

$(this).attr('href').replace("&location=100", "&location=loc");

$(this).attr('href').replace("&location=100", "&location=" + loc);

【讨论】:

    猜你喜欢
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2022-07-25
    • 2016-12-18
    • 2015-03-02
    相关资源
    最近更新 更多