我正在尝试从一个JS函数向另一个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>
发布于 2018-10-05 00:03:58
我用JQuery找到了一个简单的解决方案:
$(a).click(function(e) {
var txt = $(e.target).text();
console.log("Link: " + txt)
});
https://stackoverflow.com/questions/52635992
复制相似问题