gpt4 book ai didi

jquery - 从 .click on link 输入函数

转载 作者:行者123 更新时间:2023-11-28 00:47:05 25 4
gpt4 key购买 nike

我正在从文本输入字段中获取值。

jQuery:

$('.submitLocation').click(function(){

// get value from input field
var city = $(".city").val();
});

HTML

<input type="text" name="city" class="city" placeholder="City Name">
<button class="submitLocation">Set location</button></br>

我希望当用户点击包含历史搜索的列表项时发生同样的事情。我能够列出结果,但无法在选择列表项时再次触发该功能。

我试图通过将城市类分配给列表项然后创建一个触发初始函数的函数来解决这个问题。

var weather = [];
var weatherLength;
var text;
var i;

function showCurrent(currentWeather) {
console.log(currentWeather);
console.log(currentWeather.name);

weather.push( currentWeather.name );

if (typeof(Storage) !== "undefined") {

// Store
// saves name/s in local storage (for histoy list)
localStorage.setItem("weather", JSON.stringify( weather ) );

// saves name in session storage for current use
sessionStorage.setItem("name", currentWeather.name);

// Retrieve
// Retrieves name from session storage
document.getElementById("name").innerHTML = sessionStorage.getItem("name");

weatherLength = weather.length;
text = "<ul>";
for (i = 0; i < weatherLength; i++) {
text += "<li class='city'>" + "<a href='location.html' class='submitExistingLocation'>" + weather[i] + "</a>" + "</li>";
}
text += "</ul>";
document.getElementById("record2").innerHTML = text;

$('.submitExistingLocation').click(function(){
$('.submitLocation').click(); // Trigger search button click event
})

html

<div id="record2"></div>

最佳答案

您正在创建多个具有 CSS 类 city 的列表项在他们身上:

text = "<ul>";
for (i = 0; i < weatherLength; i++) {
text += "<li class='city'>" + "<a href='location.html' class='submitExistingLocation'>" + weather[i] + "</a>" + "</li>";
}
text += "</ul>";

然后,在您的点击事件处理程序中,您将使用 $(".city").val(); 获取值.根据documentation of .val() function在 jQuery 中:

[It gets] the current value of the first element in the set of matched elements...

请注意,在您的情况下,第一个元素不一定是被单击的元素。

要更正选择器,您可以使用 event.target属性以获取已被单击的元素,并将其存储在全局变量中,以便它在 .submitLocation 的单击处理程序中可用。 .


另一个问题是 city类(class)设置在 <li> 上元素,它没有 value 属性。所以.val()会返回 undefined .为了获取列表项中的文本,您应该调用 .text()而不是 .val() .

您的代码最终可能如下所示:

var clickedElement = undefined;
...

$('.submitLocation').click(function(){
if(clickedElement !== undefined) {
// Get the TEXT from clicked list item.
var city = $(clickedElement).text();

// Clear the value of clicked element.
clickedElement = undefined;
} else {
...
}
}

...
$('.submitExistingLocation').click(function(event){
// Keep track of the element that was clicked.
clickedElement = event.target;

//Trigger search button click event
$('.submitLocation').click();
});

关于jquery - 从 .click on link 输入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49827534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com