繁体   English   中英

如何在div onclick下添加按钮

[英]How to add a button below div onclick

我有一堆并排的div卡,使用以下显示:inline-block,我想做的是单击卡时,它在div 下方添加了一个按钮。

我正在使用jquery的after()函数来做到这一点,但是它在div的右边添加了按钮。

拜托,我该怎么做?

PS:我尝试使用append函数,但是当再次单击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() ,以防止对按钮的单击触发其他父级的单击事件。

 $(document).ready(function() { $(".card").click(function () { $(this).append('<a class="button" href="#">Button</a>'); }); }); 
 .card{ display:inline-block; position:relative; width:200px; height:100px; margin-bottom:40px; background-color:yellow; } .button{ position: absolute; bottom: -30px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <div class="card">a</div> <div class="card">b</div> <div class="card">c</div> <div class="card">d</div> <div class="card">e</div> <div class="card">f</div> <div class="card">g</div> 

我以前为论坛写过剧透的BBCodes。 概念基本相同,因此翻转它们,您会得到:

<span>
<div onclick="var s=this.parentNode.querySelector('button');s.style.display=s.style.display==''?'none':''">
<!-- put stuff here -->
</div>
<button type="button" style="display:none"><!-- put other stuff here --></button>
</span>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM