首页 > 解决方案 > 将参数从 OnClick 事件从一个 Javascript 函数传递到另一个

问题描述

我正在尝试将超链接单击中的值从一个 JS 函数传递到另一个。在这种情况下,我需要超链接文本,它是来自本地存储的键。我需要将其传递给不同的 html/JS 脚本以从那里的本地存储访问此密钥。我正在为完成这件事而费尽心思。最后一个 console.log(); 此脚本中的语句返回“链接名称:未定义”

myApp.onPageInit("saved_locations", function(page) {
  var fragment = document.createDocumentFragment();
  var parent = document.getElementById("saved");
  var node;
  // iterate localStorage
  for (var i = 0; i < localStorage.length; i++) {
    // set iteration key name
    var key = localStorage.key(i);

    // use key name to retrieve the corresponding value
    var value = localStorage.getItem(key);

    // console.log the iteration key and value
    console.log("Key: " + key + ", Value: " + value);

    let node = document.createElement("div");
    let a = document.createElement("a");
    a.className = "link";
    a.textContent = key;
    a.style.color = "blue";
    a.href = "map_G.html";

    node.appendChild(a);

    fragment.appendChild(node);
  }

  parent.appendChild(fragment);

  var myForm = document.getElementById("enter_location");

  myForm.addEventListener("submit", function saveSearchLocation(event) {
    //event.preventDefault();

    var lat = document.getElementById("Latitude").value;
    var lon = document.getElementById("Longitude").value;
    var locationStr = document.getElementById("Location").value;

    //Save location parameters to local storage
    savedLocationParams = [lat, lon, locationStr];
    window.localStorage.setItem(
      locationStr,
      JSON.stringify(savedLocationParams)
    );
  });

  for (var i in document.getElementsByClassName("link")) {
    var link = document.getElementsByClassName("link")[i];

    link.onclick = function(e) {
      linkNames = e.srcElement.attributes.textContent;
      console.log("Link names: " + linkNames);
    };
  }
});
<body>
  <div class="pages">
    <div data-page="saved_locations" id="saved" class="page navbar-through no- 
    toolbar" align="center">
      <h2><br /><u>Enter A Location<br /><br /></u></h2>
      <form id="enter_location">
        Latitude: <input type="text" id="Latitude" value=""><br> Longitude: <input type="text" id="Longitude" value=""><br> Location: <input type="text" id="Location" value=""><br>
        <input type="submit" value="Submit">
      </form>
      <h2><u>Saved Locations</u></h2>
    </div>
  </div>
</body>

标签: javascript

解决方案


我用 JQuery 找到了一个简单的解决方案:

$(a).click(function(e) {
          var txt = $(e.target).text();
          console.log("Link: " + txt)
          });

推荐阅读