简体   繁体   English

使用jQuery插入表单

[英]Insert a form with jQuery

I have a simple form (text input + submit button) that should show up when you click on any div whose class is rep. 我有一个简单的表单(文本输入+提交按钮),当你点击其类是rep的任何div时,它应该出现。

$(document).ready(function(){
    $("div.rep").click(function(){
      $(this).removeClass('rep'); // Remove the class
      $(this).append("<form action='output.php' method='post'><input type='text' name='reply'><input type='submit'></form>"); // Add the form
    });
  });

Removing the class on line three is important because clicking on the div again or selecting the new form in it should not create another new form. 删除第三行的类非常重要,因为再次单击div或在其中选择新表单不应创建另一个新表单。 It seems to succeed in removing the class, since it loses its CSS outline after I click it, but it still creates another new form when I click the div again or click the form inside it, as if it still had the class. 它似乎成功地删除了类,因为它在我单击后丢失了它的CSS轮廓,但是当我再次单击div或单击其中的表单时它仍然创建另一个新表单,就像它仍然有类一样。 Is there a way I can prevent this? 有没有办法阻止这种情况?

Here are some other things I've tried unsuccessfully: 以下是我尝试过的其他一些不成功的事情:
.html() instead of .append() (This causes it to unfocus the text box immediately after it's clicked) .html()而不是.append()(这会导致文本框在单击后立即失焦)
</div> before the form code inside of .append() and .html() (jQuery parses this out so it has no effect) 在.append()和.html()中的表单代码之前的</ div>(jQuery解析它,所以它没有效果)

Thanks in advance for your help! 在此先感谢您的帮助!

$("div.rep").click means "find an element with the rep class, then bind a function to that element's click element, even if the class is gone when the click happens". $("div.rep").click表示“使用rep类查找元素,然后将函数绑定到该元素的click元素,即使该类在单击发生时消失了”。 You want "run a function every time a click event occurs on an element that currently has the rep class". 您希望“每次在当前具有rep类的元素上发生click事件时运行函数”。

You can do this with the on function: 您可以使用on函数执行此操作:

$(document.body).on('click', 'div.rep', function() {
    // function content
});

on binds the event to an ancestor element, in this case the document's body element. on将事件绑定到祖先元素,在本例中为文档的body元素。 All click events are caught there. 所有click事件都在那里捕获。 If one originated from an element that matches the selector div.rep , the function is run. 如果一个源自与选择器div.rep匹配的元素,则运行该函数。

That's because event handlers are bound to elements not to their class names, you should unbind the event or use .one() method: 这是因为事件处理程序绑定到不属于其类名的元素,您应该取消绑定事件或使用.one()方法:

$("div.rep").one('click', function() {

However, if you have to bind a handler to the elements that have .rep class names, you can use event delegation: 但是,如果必须将处理程序绑定到具有.rep类名的元素,则可以使用事件委派:

$('#aStaticParentElement').on('click', 'div.rep', function() {
    $(this).removeClass('rep');
    // ...
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM