【问题标题】:how to select val? [priv]如何选择 val? [私人]
【发布时间】:2020-04-10 20:43:49
【问题描述】:

[更新]

嗨!这是基于我的第一个问题的更详细的问题。因此,我想根据用户在第 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”。

(我不知道为什么当你运行 sn-p 时,它没有显示选项下拉列表,但我可以在我的 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>

【问题讨论】:

  • 我发现选择的选项与地图上的点之间没有任何关系。当用户选择一个项目时,jQuery 可以并且需要告诉 Google 地图 Pin 在哪里,以及要显示的详细信息。目前,我在脚本或数据中的任何地方都看不到这些细节。您需要提供更多信息。
  • 另外,当您需要使用完整 URL 时,您在头部使用相对 URL 链接,因此您的 sn-p 无法正常工作。
  • 使用pagecontainershow 而不是pagecreate,因为后者运行一次,除非您在每个选择上附加一个新页面。
  • @Omar 它不起作用,我的选项列表将消失
  • pagecontainercreate 填充列表。 pagecontainershow 显示地图。

标签: jquery jquery-ui jquery-mobile jquery-plugins


【解决方案1】:

globalIndex 永远不会改变,它仍然是 0。arr[0].value 是 1,因此 arr[globalIndex].value 也是 1。您可能希望通过 this.value 更新 globalIndex

$(document).on("pagecreate", "#page1", function () {
    populateOptions();
    $('#myOption').on('change', function() {
    console.log( this.value );
    globalIndex = 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);
    }

    // $('#myOption').attr('value', 'this.value');   
    console.log(arr[globalIndex].value) 
    $( ":mobile-pagecontainer" ).pagecontainer( "load", "#page2", { role: "page" } );
});

【讨论】:

    【解决方案2】:

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

    $(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/

    &lt;option&gt; 元素是通过 jQuery 创建的,并在迭代数组数据时将它们附加到目标 Object。

    更新

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

    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>

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

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

    【讨论】:

    • tObj 是干什么用的?
    • 嗨!我刚刚更新了我的问题,希望它更详细让您理解:)
    • @Sunny tObj 是“目标对象”的参数名称。这个函数将允许你传入一个 jQuery 对象来追加新的&lt;option&gt; 元素。我也更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多