我有一堆 div 卡片,并排使用 display: inline-block,我想做的是当我点击卡片时,它会在下方 分区。
我正在使用 jquery 的 after() 函数来执行此操作,但它将按钮添加到 div 的右侧。
请问,我该怎么做?
PS:我尝试使用追加功能,但我有另一个功能可以在我再次点击 div 时删除按钮,所以当我点击按钮(现在是 div 的一部分)时,就像你点击了在 div 上,按钮被移除,所以它不起作用......
谢谢!
编辑...
非常感谢您的回答...
抱歉没有显示代码,这里是:
<div class = "classOfDiv">
here goes some product characteristics
</div>
$('.classOfDiv').click(
function() {
//gets the border because I need it to see if I'm clicking for the first time or second time.
var border = $(this).css("border");
//checks the border
if (border == "0px none rgb(51, 51, 51)") {
//change the border style to say that the div has been clicked
$(this).css("border", "3px solid blue");
//add the button
$(this).after("<button name = 'btnDetalhes' class = 'btn btn-primary'>Detalhes</button>");
} else {
//remove the border (now the div is diselected)
$(this).css("border", "0px none rgb(51, 51, 51)");
//remove the button
$(this).next("[name='btnDetalhes']").remove();
}
}
);
最佳答案
由于您还没有实际答案,这里有一个关于如何执行我建议的显示/隐藏的非常粗略的概念。
您需要指定“隐藏”按钮 div 的内容。如果它应该再次点击卡片,则只需将 show()
更改为 toggle
.card {
display: inline-block;
position: relative;
width: 100px;
height: 100px;
border: 1px solid black;
margin: 5px;
text-align: center;
cursor: pointer;
}
.card-button {
display: none;
position: absolute;
bottom: -22px;
left: -1px;
width: 100%;
height: 20px;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="card" onclick="$('.card-button').show()">
<p>Card Content</p>
<div class="card-button" onclick="alert('button clicked!')">
<span>BUTTON</span>
</div>
</li>
</ul>
根据对话,另一种解决方案是在事件处理程序中使用 event.stopPropogation()
来防止按钮上的点击触发其他父级的点击事件。
关于javascript - 如何在div onclick下方添加一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39154951/