javascript - 将参数从 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>
解决方案
我用 JQuery 找到了一个简单的解决方案:
$(a).click(function(e) {
var txt = $(e.target).text();
console.log("Link: " + txt)
});
推荐阅读
- rust - 如何调试 proc 宏?
- android - 由 java.lang.IllegalStateException 引起的 EmojiCompat 未初始化,库 androidx.emoji.widget.EmojiTextView
- java - 使用映射计算小写单词中字母出现次数的静态方法
- neo4j - 根据两个不同节点之间的关系查询节点
- powershell - 在 powershell 中更改 csv 文件并导出为 JSON
- sql - 如何解决没有找到数据的plsql中的错误
- regex - htaccess 通过子域访问文件夹
- pyephem - PyEphem 和 Skyfield 之间的方位角/高度差异
- c# - 创建类对象的集合
- javascript - 如何使用 React 在函数中调用 usehook?