单击要在父div中克隆的元素 -

时间:2017-04-02 17:17:09

标签: javascript jquery html css

我面临的问题是, 1. thisDiv返回单击的div名称和父级 2.我需要克隆其父div中的clicked div而不是硬编码克隆行

$('div').on('click', function(){
	var thisDiv = $(this).attr('id');
	var parentDiv = $(this).parent().attr("id");
	
          alert(thisDiv);
$("p").clone().appendTo("body");		  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div id="main">
    <div id="content">content</div>
    <div id="content2"><p>content2</p></div>
    <button id="button">show it</button>
</div>

<p>This is a paragraph.</p>

请帮忙。

1 个答案:

答案 0 :(得分:0)

如果您不希望父div触发click事件,可以将 not 选择器添加到查询中:

$('div').not('#main').on('click', function(){
	var thisDiv = $(this).attr('id');
	var parentDiv = $(this).parent().attr("id");
	
    alert(thisDiv);
    $("p").clone().appendTo("body");		  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div id="main">
    <div id="content">content</div>
    <div id="content2"><p>content2</p></div>
    <button id="button">show it</button>
</div>

<p>This is a paragraph.</p>

如果您不知道父元素的id或类,则可以停止事件传播。像这样:

$('div').on('click', function(e){
    e.stopPropagation()
	var thisDiv = $(this).attr('id');
	var parentDiv = $(this).parent();
	
    $(this).clone().appendTo(parentDiv);		  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div id="main">
    <div id="content">content</div>
    <div id="content2"><p>content2</p></div>
    <button id="button">show it</button>
</div>

<p>This is a paragraph.</p>