我在想如何在点击事件中向父对象添加元素,遇到了一些困难。
我希望实现的结果是这样的:
<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>
假设我点击按钮B2。我想要在该按钮的父级LI中添加一个新的UL,然后能够向新创建的UL中添加新的LI元素。希望这样说得清楚明白!
所以基本上,点击按钮,将具有类“newul”的新UL添加到当前所在的LI中->向新创建的UL中添加新的LI。
我目前正在使用的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>');
});
很遗憾,这种情况会产生完全不希望出现的效果,并且在各个位置添加按钮。非常感谢您能提供任何帮助。
以下是我想要实现的效果的可见示例。