gpt4 book ai didi

jQuery - 运行一次函数

转载 作者:行者123 更新时间:2023-12-01 07:15:26 25 4
gpt4 key购买 nike

我有两个 anchor 标记:

<a class="location" id="colorado" name="Colorado" href="#">co</a>
<a class="location" id="colorado" name="Colorado" href="#">co</a>

当单击其中任何一个时,我想运行一个函数,仅运行一次。我看过 jQuery 中的 .one() 但我无法让它工作。我在 click() 上所做的就是获取 ID 属性并将其存储到变量中。然后我使用该变量来填写输入表单。因为 anchor 标记都具有“位置”类,所以该函数似乎对“位置”类的所有实例都执行此操作。

$(document).ready( function() {

$('.location').click(function() { //when any a tag with class of location is clicked...

var clickedId = $(this).attr("id"); //set the ID attribute into var clickedID

$("#addressInput").val(clickedId); //set value of this input field

setTimeout( function() {
$("#addressSubmit").click(); //submit the form after 1 second of the initial click
}, 1000);

});
});

如何设置此选项,以便每次单击具有位置类别的 anchor 标记时它都可以工作,但不会对所有具有“位置”类别的任何内容重复?

最佳答案

使用.one() :

$('.location').one('click',function() { //when any a tag with class of location is clicked...

var clickedId = $(this).attr("id"); //set the ID attribute into var clickedID

$("#addressInput").val(clickedId); //set value of this input field

setTimeout( function() {
$("#addressSubmit").click(); //submit the form after 1 second of the initial click
}, 1000);

});

根据站点描述:“将处理程序附加到元素的事件。处理程序最多针对每个事件类型的每个元素执行一次。”

编辑:你只想运行一次,是吗?

$('.location').on('click',function() {        
// set value of this input field, and
document.getElementById('addressInput').value = this.id;

// remove click handlers
$('.location').off('click');

// submit the form after 1 second delay
setTimeout( function() {
document.getElementById('addressSubmit').submit();
}, 1000);
});

这将删除第一次运行时的点击事件。我还冒昧地进行了一些 de-jQuerying...您正在运行的所有功能都可以轻松地用纯 JS 完成。我还将您触发点击事件更改为仅提交表单...我认为这就是您想要做的事情。

jsFiddle provided .

关于jQuery - 运行一次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19411512/

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