gpt4 book ai didi

javascript - jQuery 事件不适用于 javascript 中的 html 表单

转载 作者:行者123 更新时间:2023-12-02 19:52:22 25 4
gpt4 key购买 nike

嘿伙计们,我在 js 中有以下代码:

$(document).ready(function(){
$(".replyLink").click(function(){
$("#form-to-"+this.id).html(htmlForm()).toggle(500);
return false;
});
function htmlForm(){
var html;
html ='<form class="comment-form" id="form-post" action="request.php" method="post">';
html +='<input type="hidden" name="post_id" value="" />';
html +='<input type="hidden" name="reply" value="" />';
html +='<table><tr><td>Name:</td><td>';
html +='<input class="name" type="text" name="name" size="20" maxlength="30"/>';
html += ......
return html;
}

//this is not working!//////////////////////////////////////////
$(".comment-form input,.comment-form textarea").focus(function(){
$(this).css({
'background-color': 'white',
'border':'1px solid #3faefc',
'box-shadow': '0px 0px 2px 1px #95d3ff'
});
});
/////////////////////////////////////////////////////////////
});

HTML 我有 e.x 的链接:

<a href='#' class="replyLink">Reply</a>

当我单击此按钮时,表单会在“某处”切换,但我无法使用代码控制 htmlForm() 上的元素!TNx

最佳答案

您无法将事件处理程序直接绑定(bind)到(尚)不存在的元素上。解决此问题的最简单的更改可能是在文档就绪处理程序中预先创建所有表单,而不是在“.replyLink”单击处理程序中一次创建一个表单。请注意,当前每次调用单击处理程序时,它都会通过设置父“#form-to-...”元素的 html 来重新创建表单,无论它是否已存在。

$(document).ready(function(){
// create the forms up front
$('[id^="form-to-"]').html(htmlForm());

$(".replyLink").click(function(){
$("#form-to-"+this.id).toggle(500); // don't set html here, just toggle
return false;
});

function htmlForm(){
/* your existing function body here */
}

$(".comment-form input,.comment-form textarea").focus(function(){
/* your existing CSS setting code here */
});
});

如果由于某种原因不符合您想要做的事情,我可以考虑其他三种方法来解决这个问题:

  1. 在创建表单元素后,在“.replyLink”点击处理程序中绑定(bind)焦点事件。

  2. 使用委托(delegate)事件处理,即使用 .delegate().on() (或者 .live() 如果你有一个非常旧的 jQuery 版本)而不是 .focus() 将事件处理程序附加到确实存在的父元素。这将自动应用于稍后添加的元素。

  3. 不要动态创建表单元素。将表单包含在初始 html 标记中,并在需要时使用 .hide().show()

关于javascript - jQuery 事件不适用于 javascript 中的 html 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9121994/

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