簡體   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