[英]Onclick works only after second click
我有一個HTML列表,看起來像
<a onclick="open_file()" id="3.txt">3.txt</a>
我的open_file()
函數正在查找這個
function open_file() {
$("a").click(function (event) {
var file_name = event.target.id;
$("#f_name").val(file_name);
$.ajax({
url: "docs/" + file_name,
dataType: "text",
success: function (data) {
$("#text_form").val(data);
$('#text_form').removeAttr('readonly');
$('#delete_button').removeAttr('disabled');
$('#save_button').removeAttr('disabled');
}
})
});
}
問題是函數最終只在兩次點擊這樣的鏈接后才將數據加載到所有字段( text_form
和f_name
)。 它工作即使我第一次點擊一個文件,然后點擊另一個文件,它加載。 有沒有什么辦法解決這一問題?
你目前正在做的是將一個onclick事件添加到一個鏈接,該鏈接調用一個函數,該函數通過jQuery添加另一個onclick事件 。
刪除onclick
屬性和open_file()
函數包裝器,以便jQuery按預期添加事件。
你不需要onclick="open_file()"
這個:
<div id='linkstofiles'>
<a id="3.txt">3.txt</a>
//other links go here
</div>
$("#linkstofiles a").click(function (event) {
var file_name = event.target.id;
$("#f_name").val(file_name);
$.ajax({
url: "docs/" + file_name,
dataType: "text",
success: function (data) {
$("#text_form").val(data);
$('#text_form').removeAttr('readonly');
$('#delete_button').removeAttr('disabled');
$('#save_button').removeAttr('disabled');
}
})
});
在html中單擊onclick
時,不需要再次在函數中綁定click事件。
另外,對於$ is not defined
,您需要將jquery庫放在頭部。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.