javascript - 在这种情况下使用 jquery 获取原始 url

标签 javascript jquery html forms

在下面的表单中,我更改了 action 属性并提交了表单。那很好用。发生的事情是:如果当前位置是 http://localhost/search/?mod=all 并且搜索词是 14,则操作将更改为 http://localhost/search/?mod=all&handle=14 浏览器中的 url 也是如此。

但下次我尝试搜索时,因为现在的 url 是 http://localhost/search/?mod=all&handle=14,我得到 http://localhost/搜索/?mod=all&handle=14&handle=15。它会随着每个搜索词继续进行下去。

知道如何通过这一切保留原始 url http://localhost/search/?mod=all 吗?

这是表格:

<form method="GET" class="modForm" action="">
<input type="text" placeholder="Search" class="modSearchValue">
<input type="radio" name="text" value="text" class="text" title="Search">
</form>

这是jquery:

$('.modForm').submit(function(event) {
  var $this = $(this);
  var query = $this.find('.modSearchValue').val(); // Use val() instead of attr('value').
  var locale = window.location;
  if ($('.text').is(':checked')) {
    query = '&text=' + query;
  } else {
    query = '&handle=' + query;
  }
  route = locale + query;
  console.log(route);
  if (query.length >= 1) {
    // Use URI encoding
    var newAction = (route);
    console.log(newAction); // DEBUG
    // Change action attribute
    $this.attr('action', newAction);
    //event.preventDefault();
  } else {
    console.log('Invalid search terms'); // DEBUG
    // Do not submit the form
    event.preventDefault();
  }
});

最佳答案

有几种方法可以做到这一点。我宁愿不弄乱 window.location 并做一些更简单的事情:

<form method="GET" class="modForm" action="">
    <input type="hidden" name="mod" value="all"> <!-- mod is a hidden variable -->
    <input type="text" id="modSearchValue">      <!-- name not defined yet -->
    <input type="checkbox" id="textOrHandle">    <!-- name not required -->
</form>
$(".modForm").submit(function() {
    $("#modSearchValue").attr("name", $("#textOrHandle").is(":checked") ? "text" : "handle");
    // let the form submit!
});

关于javascript - 在这种情况下使用 jquery 获取原始 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14109234/

相关文章:

javascript - 在做某事之前如何确认所有复选框都已选中?

javascript - 如何从包含 HTML 的变量中获取正文内容?

jquery - 单击时保持链接颜色直到单击另一个链接

javascript - 表上的 jquery 过滤器第一次工作,但之后隐藏所有行

javascript - 如何使用控制台更改 javascript 中选择标签中的选项?

javascript - 如何将类添加到相邻元素的输入元素?

jquery - 不确定我是否完全理解 jQuery 委托(delegate)

javascript - 选择数组内的元素

html - 具有奇数/偶数行自定义样式的动态 CSS 网格

html - 如何在所有内容下方的 <table> 中添加按钮?