简体   繁体   中英

Displaying bootstrap alert message box when an anchor is clicked

I have an anchor element which removes items when it is clicked. I am trying to show bootstrap danger alert message box (NOT alert window) when the anchor tag is clicked. i am trying to achieve this without wrapping the anchor in div. any help is appreciated.

 $(document).ready(function(){ $('.remove-item').click(function(){ $('.alert').show() setTimeout(function(){ $(".remove-item").hide(); }, 2000); }); }); 
 .alert{ display: none; } 
 <a href="#" class="btn btn-danger remove-item" data-dismiss="alert" data-code="<?php echo $product_code; ?>"><i class="glyphicon glyphicon-trash"></i></a> 

Here is a little solution you can rely on. It is in vanillia JS.

HTML

<button class="anchor">test 1</button>
<button class="anchor">test 2</button>
<button class="anchor">test 3</button>
<button class="anchor">test 4</button>

<div id="alert">
<strong>Are you sure?</strong>
<button id="alert-ok">ok</button>
</div>

CSS

#alert {
  display: none;
}

JS

var buttons = document.getElementsByClassName('anchor');

var alertBox = document.getElementById("alert");

var alertBoxOk = document.getElementById("alert-ok");


Array.prototype.forEach.call(buttons, function (btn) {
    btn.addEventListener("click", function (event) {
  var toRemove = event.target;
  alertBox.style.display = "block";
  console.log(toRemove);
  alertBoxOk.addEventListener("click", function() {
    toRemove.remove();
    alertBox.style.display = "none";
  });
  })
});

function deleteAnchor() {
    this.remove();
}

And the fiddle: fiddle

There is no problem with the classes your are using for the Bootstrap alert and no problem with the click event either, but UNEXPECTED END OF INPUT means that there is a class or a function that is not closed. In your case, you declared two functions, but only one is closed... :

$(document).ready(function(){
  $('.remove-item').click(function(){
  $('.alert').show()
  setTimeout(function(){
     $(".remove-item").hide(); 
  }, 2000);
});

Uncaught ReferenceError: $ is not defined means that the JQuery library is not installed... Do you have the required script tag ? Something like :

<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
crossorigin="anonymous"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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