首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将参数从OnClick事件从一个Javascript函数传递到另一个

将参数从OnClick事件从一个Javascript函数传递到另一个
EN

Stack Overflow用户
提问于 2018-10-04 05:33:32
回答 1查看 579关注 0票数 0

我正在尝试从一个JS函数向另一个JS函数传递一个超链接点击的值。在这个上下文中,我需要超链接文本,它是本地存储中的一个键。我需要把它传递给一个不同的html/JS脚本,以便从本地存储中访问这个密钥。我花了一段时间来完成这件事。此脚本中的最后一条console.log();语句返回“链接名称:未定义”

代码语言:javascript
复制
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);
    };
  }
});
代码语言:javascript
复制
<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>

EN

回答 1

Stack Overflow用户

发布于 2018-10-05 00:03:58

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

代码语言:javascript
复制
$(a).click(function(e) {
          var txt = $(e.target).text();
          console.log("Link: " + txt)
          });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52635992

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档