首页 > 解决方案 > 如何选择 val?[私人]

问题描述

[更新]

你好!这是基于我的第一个问题的更详细的问题。因此,我想根据用户在第 1 页中选择的选项更改第 2 页上的地图指针。

示例:用户在第 1 页选择雨伞,单击“立即查找”按钮并在第 2 页的地图上显示地图指针“Clementi 7-11”和“Cheers Buona Vista”。但是,如果用户在页面上选择润唇膏,请单击“立即查找”按钮,它将在第 2 页的地图上显示用户地图指针“SP 7-11”和“Cheers Bouna Vista”。

目前,我的问题是,无论用户在第 1 页选择了什么,它都会在第 2 页的地图上始终显示地图指针“Clementi 7-11”和“Cheers Buona Vista”。

(我不知道为什么当你运行代码片段时,它没有显示选项下拉列表,但我可以在我的 VSC 中完成,我也可以显示我的谷歌地图和地图指针)

var arr = [{
    img: 'umbrella.png',
    item: 'Umbrella',
    price: '$10',
    value: 1,
    qty: 0
  },
  {
    img: 'lipbalm.png',
    item: 'Lip Balm',
    price: '$5',
    value: 2,
    qty: 0
  },
  {
    img: 'flu.png',
    item: 'Flu Medication',
    price: '$5',
    value: 3,
    qty: 0
  },
  {
    img: 'glucose.png',
    item: 'Glucose Sweets',
    price: '$1',
    value: 4,
    qty: 0
  }
];
var globalIndex = 0;

//Page 1 Select
function populateOptions() {
  console.log('populateOptions');

  var o = "";
  $.each(arr, function(index, val) {
    console.log("index:" + index);
    var item = arr[index].item;
    o = o + "<option value='" + arr[index].value + "'>" + item + "</option>";
    console.log(arr[index].value)
  });
  $("#myOption").html(o);
  $("#myOption").selectmenu("refresh");
};

$(document).on("pagecreate", "#page1", function() {
  populateOptions();
  $('#myOption').on('change', function() {
    console.log(this.value);
    if (this.value == 2) {
      $('option').attr('value', 2);
    } else if (this.value == 3) {
      $('option').attr('value', 3);
    } else if (this.value == 4) {
      $('option').attr('value', 4);
    } else {
      $('option').attr('value', 1);
    }
    console.log(arr[globalIndex].value)
    $(":mobile-pagecontainer").pagecontainer("load", "#page2", {
      role: "page"
    });
  });
  $("#myOption").selectmenu("refresh", true);

});

//Page 2
$(document).on("pagecreate", "#page2", function() {
  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: {
      lat: 11.3083,
      lng: 103.7776
    },
    zoom: 14,
    mapTypeId: 'roadmap'
  });
});

// //Umbrella Stores     
var umbrellaPoints = [{
    latitude: 1.315680,
    longitude: 103.764976,
    title: "Clementi 7-11",
    content: "<h3>Clementi 7-11</h3>"
  },

  {
    latitude: 1.307567,
    longitude: 103.789972,
    title: "Cheers Buona Vista",
    content: "<h3>Cheers Buona Vista</h3>"
  },
];

// //Lip Balm Stores
var lipBalmPoints = [{
    latitude: 1.311639,
    longitude: 103.778665,
    title: "SP 7-11",
    content: "<h3>SP 7-11</h3>"
  },

  {
    latitude: 1.307567,
    longitude: 103.789972,
    title: "Cheers Buona Vista",
    content: "<h3>Cheers Buona Vista</h3>"
  },
];

// //Flu Medicine Stores
var fluMedPoints = [{
    latitude: 1.303444,
    longitude: 103.792011,
    title: "Cheers Biopolis Street",
    content: "<h3>Cheers Biopolis Street</h3>"

  },

  {
    latitude: 1.311639,
    longitude: 103.778665,
    title: "SP 7-11",
    content: "<h3>SP 7-11</h3>"
  }
];

// //Glucose Sweets Stores
var gluSweetPoints = [{
    latitude: 1.315680,
    longitude: 103.764976,
    title: "Clementi 7-11",
    content: "<h3>Clementi 7-11</h3>"
  },

  {
    latitude: 1.303444,
    longitude: 103.792011,
    title: "Cheers Biopolis Street",
    content: "<h3>Cheers Biopolis Street</h3>"

  }
];


function findMe() {
  $('#popupDialogue').popup();
  $('#popupDialogue').popup('open');
  navigator.geolocation.getCurrentPosition(onFindSuccess, onError);
};

function onFindSuccess(position) {
  $('#popupDialogue').popup('close');
  var latlong = new google.maps.LatLng(position.coords.latitude,
    position.coords.longitude);
  var mapProp = {
    center: latlong,
    zoom: 18,
    mapTypeId: google.maps.MapTypeId.HYBRID
  };
  var map = new google.maps.Map(document.getElementById("map-canvas"), mapProp);
  var content = "<h3>You are here</h3>";
  var title = "Your position";
  addMarkersToMap(map, latlong, title, content);
}

function onError(error) {
  alert("Encounter an error")
}

function addMarkersToMap(map, latlong, title, popcontent) {
  var marker = new google.maps.Marker({
    position: latlong,
    map: map,
    title: title
  });

  var infowindow = new google.maps.InfoWindow({
    content: popcontent
  });

  infowindow.open(map, marker);
}

function showPoints() {
  var latlong = new google.maps.LatLng(1.311166, 103.775583);
  var mapProp = {
    center: latlong,
    zoom: 14,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map-canvas"), mapProp);

  $('#findNow').click(function() {
    console.log(this.value)

  });
  console.log(arr[globalIndex].value);

  if (arr[globalIndex].value == 1) {
    $.each(umbrellaPoints, function(index, val) {
      var latlong2 = new google.maps.LatLng(val.latitude, val.longitude);
      addMarkersToMap(map, latlong2, val.title, val.content);
    });
  } else if (arr[globalIndex].value == 2) {
    $.each(lipBalmPoints, function(index, val) {
      var latlong3 = new google.maps.LatLng(val.latitude, val.longitude);
      addMarkersToMap(map, latlong3, val.title, val.content);
    });
  } else if (arr[globalIndex].value == 3) {
    $.each(fluMedPoints, function(index, val) {
      var latlong4 = new google.maps.LatLng(val.latitude, val.longitude);
      addMarkersToMap(map, latlong4, val.title, val.content);
    });
  } else if (arr[globalIndex].value == 4) {
    $.each(gluSweetPoints, function(index, val) {
      var latlong5 = new google.maps.LatLng(val.latitude, val.longitude);
      addMarkersToMap(map, latlong5, val.title, val.content);
    });
  }

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
  <script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyD7WcthdB_FxP0wUX1rRgJCDHiw2IpqUz0"></script>
</head>

<body>
  <!-- Page 1 -->
  <div data-role="page" id="page1">
    <div data-role="main" class="ui-content" id="page1main" style="margin-top: 250px;">
      <label for="select">Tell me what are you looking for today:</label>
      <select name="select" class="selectItem" id="myOption"></select>
      <br>
      <button style="width: 70%; margin-left: auto; margin-right: auto;" id="findNow">
              <a href="#page2" data-transition="flip"onclick="showPoints()">Find Now</a>
            </button>
    </div>
  </div>

  <!-- Page 2 -->
  <div data-role="page" id="page2">
    <div data-role="header">
      <a href="#page1" class="ui-btn ui-icon-home ui-btn-icon-left ui-corner-all ui-btn-icon-notext"></a>
      <h1>Google Maps</h1>
      <a data-rel="back" data-role="button" data-icon="arrow-l" data-iconpos="left">Go back</a>
    </div>
    <div data-role="main" class="ui-content">
      <div id='content'>
        <p><button class="ui-button" onclick="findMe()">Find Me</button></p>
        <p><button class="ui-button" onclick="showPoints()">Places of interest</button></p>
        <div id="map-canvas"></div>
      </div>
    </div>
    <div data-role="popup" id="popupDialogue" data-dismissible="false" style="max-width:400px;">
      <div data-role="header">
        <h1>Map loading...</h1>
      </div>
      <div role="main" class="ui-content">
        <h3 class="ui-title">Retrieving current position... please wait</h3>
      </div>
    </div>
  </div>
</html>

标签: jqueryjquery-uijquery-mobilejquery-plugins

解决方案


你的例子不是很清楚,逻辑也不清楚,因为它是一个有限的例子。考虑以下代码。

$(function() {
  var arr = [{
      img: 'umbrella.png',
      item: 'Umbrella',
      price: '$10',
      value: 1,
      qty: 0
    },
    {
      img: 'lipbalm.png',
      item: 'Lip Balm',
      price: '$5',
      value: 2,
      qty: 0
    },
    {
      img: 'flu.png',
      item: 'Flu Medication',
      price: '$5',
      value: 3,
      qty: 0
    },
    {
      img: 'glucose.png',
      item: 'Glucose Sweets',
      price: '$1',
      value: 4,
      qty: 0
    }
  ];

  function populateOptions(d, tObj) {
    console.log("Populate Options", tObj.attr("id"));
    tObj.html("");
    $.each(d, function(i, v) {
      $("<option>", {
        id: "select-opt-" + (i + 1),
        value: v.value
      }).html(v.item).appendTo(tObj);
    });
    tObj.selectmenu("refresh");
  };

  $("#myOption").selectmenu();
  populateOptions(arr, $("#myOption"));

  $('#myOption').on('change', function() {
    var p = $(this).val();
    console.log("Selected", p);
    $(":mobile-pagecontainer").pagecontainer("load", "#page" + p, {
      role: "page"
    });
  });
});
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
<div data-role="page">
  <div data-role="main" class="ui-content" id="page1main" style="margin-top: 250px;">
    <select name="select" class="selectItem" id="myOption"></select>
  </div>
</div>

你使用的方式没有意义$.each()

$.each()函数可用于迭代任何集合,无论是对象还是数组。在数组的情况下,回调每次都会传递一个数组索引和一个对应的数组值。

这种情况下的值是一个对象。所以你不需要使用索引来获取对象,它已经可用。查看更多:https ://api.jquery.com/jquery.each/

这些<option>元素是通过 jQuery 创建的,并在迭代数组数据时将它们附加到目标对象。

更新

制作更复杂的数据集可能会更好。

var itemData = {
  Umbrella: {
    img: "umbrella.png",
    item: "Umbrella",
    price: 10,
    locations: [{
        latitude: 1.315680,
        longitude: 103.764976,
        title: "Clementi 7-11",
        content: "<h3>Clementi 7-11</h3>"
      },
      {
        latitude: 1.307567,
        longitude: 103.789972,
        title: "Cheers Buona Vista",
        content: "<h3>Cheers Buona Vista</h3>"
      }
    ]
  },
  "Lip Balm": {
    img: "lipbalm.png",
    item: "Lip Balm",
    price: 5,
    locations: [{
        latitude: 1.311639,
        longitude: 103.778665,
        title: "SP 7-11",
        content: "<h3>SP 7-11</h3>"
      },
      {
        latitude: 1.307567,
        longitude: 103.789972,
        title: "Cheers Buona Vista",
        content: "<h3>Cheers Buona Vista</h3>"
      }
    ]
  },
  "Flu Medication": {
    img: "flu.png",
    item: "Flu Medication",
    price: 5,
    locations: [{
        latitude: 1.303444,
        longitude: 103.792011,
        title: "Cheers Biopolis Street",
        content: "<h3>Cheers Biopolis Street</h3>"
      },
      {
        latitude: 1.311639,
        longitude: 103.778665,
        title: "SP 7-11",
        content: "<h3>SP 7-11</h3>"
      }
    ]
  },
  "Glucose Sweets": {
    img: "glucose.png",
    item: "Glucose Sweets",
    price: 1,
    locations: [{
        latitude: 1.315680,
        longitude: 103.764976,
        title: "Clementi 7-11",
        content: "<h3>Clementi 7-11</h3>"
      },
      {
        latitude: 1.303444,
        longitude: 103.792011,
        title: "Cheers Biopolis Street",
        content: "<h3>Cheers Biopolis Street</h3>"
      }
    ]
  }
};

$(function() {
  function populateOptions(d, tObj) {
    console.log("Populate Options", tObj.attr("id"));
    tObj.html("");
    var i = 1;
    $.each(d, function(k, v) {
      $("<option>", {
        class: "select-opt-" + i,
        value: k
      }).html(k).appendTo(tObj);
      i++;
    });
    tObj.selectmenu("refresh");
  };

  function findMe() {
    $('#popupDialogue').popup();
    $('#popupDialogue').popup('open');
    navigator.geolocation.getCurrentPosition(onFindSuccess, onError);
  };

  function onFindSuccess(position) {
    $('#popupDialogue').popup('close');
    var latlong = new google.maps.LatLng(position.coords.latitude,
      position.coords.longitude);
    var mapProp = {
      center: latlong,
      zoom: 18,
      mapTypeId: google.maps.MapTypeId.HYBRID
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"), mapProp);
    var content = "<h3>You are here</h3>";
    var title = "Your position";
    addMarkersToMap(map, latlong, title, content);
  }

  function onError(error) {
    alert("Encountered an error");
  }

  function addMarkersToMap(map, latlong, title, popcontent) {
    var marker = new google.maps.Marker({
      position: latlong,
      map: map,
      title: title
    });

    var infowindow = new google.maps.InfoWindow({
      content: popcontent
    });

    infowindow.open(map, marker);
  }

  function showPoints() {
    var latlong = new google.maps.LatLng(1.311166, 103.775583);
    var mapProp = {
      center: latlong,
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"), mapProp);
  }

  $('#findNow').click(function() {
    $(":mobile-pagecontainer").pagecontainer("load", "#page2", {
      role: "page"
    });
  });

  $("#myOption").selectmenu();
  populateOptions(itemData, $("#myOption"));

  $('#myOption').on('change', function() {
    var item = itemData[$(this).val()];
    console.log("Selected", item);
    var map = new google.maps.Map($("#map-canvas")[0], {
      center: {
        lat: -34.397,
        lng: 150.644
      },
      zoom: 8
    }), latlong;
    $.each(item.locations, function(i, l) {
      latlong = new google.maps.LatLng(l.latitude, l.longitude);
      addMarkersToMap(map, latlong, l.title, l.content);
    });
    showPoints();
  });
});
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
  <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
  <script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyD7WcthdB_FxP0wUX1rRgJCDHiw2IpqUz0"></script>
</head>

<body>
  <!-- Page 1 -->
  <div data-role="page" id="page1">
    <div data-role="main" class="ui-content" id="page1main" style="margin-top: 250px;">
      <label for="select">Tell me what are you looking for today:</label>
      <select name="select" class="selectItem" id="myOption"></select>
      <br>
      <button style="width: 70%; margin-left: auto; margin-right: auto;" id="findNow">
              <a href="#page2" data-transition="flip">Find Now</a>
            </button>
    </div>
  </div>

  <!-- Page 2 -->
  <div data-role="page" id="page2">
    <div data-role="header">
      <a href="#page1" class="ui-btn ui-icon-home ui-btn-icon-left ui-corner-all ui-btn-icon-notext"></a>
      <h1>Google Maps</h1>
      <a data-rel="back" data-role="button" data-icon="arrow-l" data-iconpos="left">Go back</a>
    </div>
    <div data-role="main" class="ui-content">
      <div id='content'>
        <p><button class="ui-button" onclick="findMe()">Find Me</button></p>
        <p><button class="ui-button" onclick="showPoints()">Places of interest</button></p>
        <div id="map-canvas"></div>
      </div>
    </div>
    <div data-role="popup" id="popupDialogue" data-dismissible="false" style="max-width:400px;">
      <div data-role="header">
        <h1>Map loading...</h1>
      </div>
      <div role="main" class="ui-content">
        <h3 class="ui-title">Retrieving current position... please wait</h3>
      </div>
    </div>
  </div>

</html>

由于代码片段的工作方式,上面的示例将无法正常工作。您可以在此处看到itemData是结构化对象。这使您可以关联每个项目的相关数据,例如携带该产品的商店位置。如果您有更多的位置,您可能会考虑向服务器执行 AJAX 请求以搜索/检索位置列表。

进行选择时,会为这些位置添加标记。当用户点击“Fine Now”时,页面 2 将被加载并且应该包含带有标记的地图。


推荐阅读