Sin*_*mok 6 html javascript jquery
我在查找如何在click事件上向父对象添加元素时遇到了一些麻烦.
我希望实现的结果是:
<ul>
<li><button>B1</button>
<ul class="newul">
<li><button>B1.1</button>
<ul class="newul">
<li><button>1.1.1</button></li>
<li><button>1.1.2</button></li>
</ul>
</li>
<li><button>B1.1</button></li>
</ul>
</li>
<li><button>B2</button></li>
<li><button>B3</button></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
假设我点击按钮B2.我希望将新的UL添加到该按钮的父LI,然后能够将新的LI元素添加到新创建的UL中.我希望这是有道理的!
基本上,单击按钮,将新的UL与类"newul"添加到您当前所在的LI中 - >将新LI添加到新创建的UL中.
我目前使用的jquery如下:
$('button').click(function(){
//Get parent..
var parent = $(this).parent();
//Add a new UL to the parent and save it as newul
var newul = parent.add("ul");
//Add the class to the new UL
newul.addClass('newul');
//Add a new li to the new UL
newli = newul.add('li');
//Add a button to the new LI
newli.append('<button></button>');
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,这产生了完全不受欢迎的影响,并且到处都是按钮.我很感激您提供的任何帮助.
这是我所追求的一个可见的例子.顶部是效果id喜欢实现.
即使@am不是我有正确的代码.没有解释你的代码失败的原因,我认为这就是你要求的答案.
您的代码中存在几个问题:
第一
//Add a new UL to the parent and save it as newul
var newul = parent.add("ul");
Run Code Online (Sandbox Code Playgroud)
它'ul'是一个选择器,因此将在DOM中搜索其他<ul>元素,而不是创建一个新元素.此外,parent.add()方法返回parent对象,而不是您选择的ul.
正确的代码:
//Add a new UL to the parent and save it as newul
var newul = $("<ul>").appendTo(parent);
Run Code Online (Sandbox Code Playgroud)
第二:
//Add a new li to the new UL
newli = newul.add('li');
Run Code Online (Sandbox Code Playgroud)
同样的问题,因为newul实际上仍然是parent你得到所有类型的疯狂.此外,你错过了一个var,但也许我只是没有得到你的关闭.
正确的代码:
//Add a new li to the new UL
var newli = $("<li>").appendTo(newul);
Run Code Online (Sandbox Code Playgroud)
就这样.如果您在代码中修复它,它将起作用.
但是,除非您确实需要这些引用持久化,否则如果将整个事物作为字符串传递,通常会获得更好的性能:
$('button').click( function() {
$(this).parent()
.append(
$('<ul class="newul"><li><button></li></ul>')
);
});
Run Code Online (Sandbox Code Playgroud)
如果您希望所有新按钮具有相同的功能,请使用on()方法和按钮类:
$('body').on('click', 'button.ul-appending', function() {
$(this).parent()
.append(
$('<ul class="newul"><li><button class="ul-appending"></li></ul>')
);
});
Run Code Online (Sandbox Code Playgroud)
您可以将'body'选择器更改为更具体的内容,以便在页面上的每次单击时都不会查询.只需确保将类添加ul-appending到此处理程序未生成的所有现有按钮.
| 归档时间: |
|
| 查看次数: |
28784 次 |
| 最近记录: |