Javascript Jquery追加输入元素并从该输入元素发送数据
我有以下简单的HTML代码:Javascript Jquery追加输入元素并从该输入元素发送数据,javascript,jquery,Javascript,Jquery,我有以下简单的HTML代码: <div id="new_gallery"> <p id="add_gallery">Add new gallery</p> </div> 添加新库 和jQuery代码: <script> $("#add_gallery").click(function() { $("#new_gallery").append('<input name"new_gallery"
<div id="new_gallery">
<p id="add_gallery">Add new gallery</p>
</div>
添加新库
和jQuery代码:
<script>
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" /><a href="#" id="create_new_gallery">Add</a>');
$(this).remove();
});
$("#create_new_gallery").on('click', function(){
alert('1');
});
</script>
$(“#添加#库”)。单击(函数(){
$(“#新画廊”)。附加(“”);
$(this.remove();
});
$(“#创建#新#库”)。在('单击',函数()上{
警报(“1”);
});
第一个功能正常,但第二个功能不正常。我需要创建新的input
元素,通过ajax发送数据,然后删除input
元素并再次附加p
元素。如何执行此操作?\create\u new\u当您绑定其单击事件时,库
不存在
以下是您的代码的外观:
$("#add_gallery").click(function() {
var newG = $("#new_gallery");
$('<input name"new_gallery" />').appendTo(newG);
$('<a href="#" id="create_new_gallery">Add</a>').appendTo(newG).on('click',
function() {
alert('1');
});
$(this).remove();
});
$(“#添加#库”)。单击(函数(){
var newG=$(“新画廊”);
$('')。附录(新增);
$('').appendTo(newG).on('单击',
函数(){
警报(“1”);
});
$(this.remove();
});
请注意,将
$(“#new_gallery”)
放入一个变量中时,避免查找它两次。当第二条语句运行时,元素#create_new_gallery
还不存在,因此它什么也不做
您可以在创建元素后绑定到click事件。例如,这确保元素存在于DOM中:
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name="new_gallery" /><a href="#" id="create_new_gallery">Add</a>');
$(this).remove();
$("#create_new_gallery").on('click', function() {
alert('1');
});
});
$(“#添加#库”)。单击(函数(){
$(“#新画廊”)。附加(“”);
$(this.remove();
$(“#创建#新#库”)。在('单击',函数()上{
警报(“1”);
});
});
这里有一个更优化的版本。追加一个元素并重新查询它(尽管按id查询是最快的方法,但事件)是没有意义的。此外,最好还是使用jQuery的链接功能:
$("#add_gallery").click(function() {
var $gallery = $("#new_gallery");
$('<input name="new_gallery" />').appendTo($gallery);
$('<a href="#" id="create_new_gallery">Add</a>')
.on('click', function() {
alert('1');
})
.appendTo($gallery);
$(this).remove();
});
$(“#添加#库”)。单击(函数(){
var$gallery=$(“新画廊”);
$('')。附录($图库);
$('')
.on('单击',函数()){
警报(“1”);
})
.appendTo($画廊);
$(this.remove();
});
尝试
live
处理加载页面后添加的元素激发的事件
$("#create_new_gallery").live('click', function(){
alert('1');
});
$(文档).ready(函数(){
$(“#添加#库”)。单击(函数(){
$(“#新画廊”)。附加(“”);
$(this.remove();
$(“#创建#新#库”)。在('单击',函数()上{
警报(“1”);
});
});
});
演示:
live()
已被弃用。请改用delegate()
或on()
。遗憾的是,必须在代码的同一部分中创建和选择create\u new\u gallery
。请查看我的答案。
$(document).ready(function () {
$("#add_gallery").click(function() {
$("#new_gallery").append('<input name"new_gallery" /><a href="#" id="create_new_gallery">Add</a>');
$(this).remove();
$("#create_new_gallery").on('click', function(){
alert('1');
});
});
});