如何将函数search_click()设置为两个以上的request_url

时间:2018-06-10 10:33:33

标签: javascript jquery

我想知道如何将函数search_click()设置为两个以上request_url

我有function search_click,如下所示,我有三种不同的request_url用户类型:

function search_click() {
  var type = $('#jsSelectOption').attr('data-value'),
    keywords = $('#search_keywords').val(),
    request_url = '';
  if (keywords == "") {
    return
  }
  if (type == "test") {
    request_url = "/admin?keywords=" + keywords
  } else if (type == "user") {
    request_url = "/admin/user?keywords=" + keywords
  }
}

我尝试使用下面的代码更改上面的代码,但它不起作用。

function search_click() {
  var type = $('#jsSelectOption').attr('data-value'),
    keywords = $('#search_keywords').val(),
    request_url = '';
  if (keywords == "") {
    return
  }
  if (type == "test") {
    request_url = "/admin?keywords=" + keywords
    request_url = "/admin_a?keywords=" + keywords
    request_url = "/admin_b?keywords=" + keywords
  } else if (type == "user") {
    request_url = "/admin/user?keywords=" + keywords
    request_url = "/admin_a/user?keywords=" + keywords
    request_url = "/admin_b/user?keywords=" + keywords
  }
}

1 个答案:

答案 0 :(得分:0)

只需将request_url用作数组[],然后将所有网址推入其中

见下面的代码:

function search_click() {
  var type = $('#jsSelectOption').val(),
    keywords = $('#search_keywords').val(),
    //here you declar your var as an array .
    request_url = [];
  if (keywords == "") {
    return
  }
  
  if (type == "test") {
    request_url.push("/admin?keywords=" + keywords);
    request_url.push("/admin_a?keywords=" + keywords);
    request_url.push("/admin_b?keywords=" + keywords);
  } else if (type == "user") {
    request_url.push("/admin/user?keywords=" + keywords);
    request_url.push("/admin_a/user?keywords=" + keywords);
    request_url.push("/admin_b/user?keywords=" + keywords);
  }
  
  alert("values = \n"+request_url.toString().split(',').join("\n"))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="keyword" id="search_keywords" />

<select id="jsSelectOption" >
  <option ></option>
  <option >test</option>
  <option >user</option>
</select>

<button onclick="search_click()">search</button>