On Change从数组中导航到url值

时间:2017-11-15 20:12:52

标签: jquery

我有一个选择菜单,它从一组对象中提取所有选项。见下文。我希望菜单导航到每个状态的更改的url值并在新选项卡中打开,但我所拥有的是没有正确触发。我有一个if / else语句,因为它没有识别url值而继续触发'false'。

let states = [
      {id: 1, state: "Alabama", district: "1st District", url:"www.google.com"},
      {id: 2, state: "Alabama", district: "2nd District", url:"www.google.com"},
      {id: 3, state: "Alabama", district: "3rd District", url:"www.google.com"},
      {id: 4, state: "Alabama", district: "4th District", url:"www.google.com"},
      {id: 5, state: "Alabama", district: "5th District", url:"www.google.com"},
      {id: 6, state: "Alabama", district: "6th District", url:"www.google.com"},
      {id: 7, state: "Alabama", district: "7th District", url:"www.google.com"},
      {id: 9, state: "Alaska", district: "Statewide District", url:"www.google.com"},
      {id: 10, state: "Arizona", district: "1st District", url:"www.google.com"},
      {id: 11, state: "Arizona", district: "2nd District", url:"www.google.com"},
      {id: 12, state: "Arizona", district: "3rd District", url:"www.google.com"},  

还有更多州,但上面只是一个片段。

<body>
    <div class="container55">
      <h2>Find Out How Tax Reform Will Impact Your District</h2>
        <select id="listed_states">
          <option>Find Your District Here</option>
        </select>
    </div>
  </body>


   <script>
    $(document).ready(function() {
  //Code block generating dropdown list from states object
      for (let i = 0; i < states.length; i++) {
       if (states[i].id > 0) {
        var option = $("<option>", {
         text: states[i].state + " " + states[i].district,
         value: states[i].id
       });
      $('#listed_states').append($(option));
    }
  }



  $('#listed_states').on('change', function(){
   if ($(this).url){
    window.open($(this).url, '_blank');
   } else {
    console.log('false');
   }
  })
 });
 </script>

1 个答案:

答案 0 :(得分:1)

选项缺少网址,你用$(this)更改$(this).url .find('option:selected')。attr('url')

DBusArgument

https://codepen.io/piscu/pen/eeGzBP