JQuery.click () method not working properly

I wrote a function that, when you click on a specific element, would replace the div with a hidden range. When I had an event handler in the "onclick =" attr tag, the function worked fine. But then I tried to get a "quirkiness" and replace onclick attr with the jQuery.click () method. Now, when I try to use it on the page, nothing but clunk - nothing happens.

However, if I execute the exact code in the Chrome js console, it works fine. Here is my js:

$("a#delete").click(function () {
    $("a#delete").replaceWith($("span.hconf").attr("style", "none"))
});

Here is the corresponding html (inside inside div, outside):

<a class='modify' id="delete" u="{{ i.id }}" href='#'>delete</a>
<span class='hconf' style="display:none;">Are you sure? <a class='confirm' id='del_conf_true' onclick='deltrue();' href='#'>yes</a> | <a class='confirm' id='del_conf_false' href='#'>no</a></span>

I know that I can change the second $ ("a # delete") with the keyword "this", but I leave it canceled now, as I'm not sure if this part of the problem. I am new to js / jQuery.

+3
source share
3 answers

Ready it:

$(document).ready(function() {
    $("a#delete").click(function () {
        $(this).replaceWith($("span.hconf").attr("style", "display:none"));
    });
});

... and you don't mean style = "display: none"? You can just as easily use .hide():

$("span.hconf").hide();

And finally, it makes no sense to use a filter tag in the identifier selector. Just do it $("#delete"), it will be shorter and faster.

+5
source

, "". , jQuery "a # delete" , . "" :

$(function() {
  $('a#delete').click(function() { /* ... */ });
});

, . script <body>.

+2

This JS starts before the DOM is ready, try putting this code inside a block $(function(){})(DOM ready).

$(function(){
  $("a#delete").click(function () {
    $("a#delete").replaceWith($("span.hconf").attr("style", "display:none"));
  });
});

Or you can try using .live.

  $("a#delete").live('click', function () {
    $("a#delete").replaceWith($("span.hconf").attr("style", "display:none"));
  });

NOTE. Use .hide()and .show()to change the display attribute.

+1
source

Source: https://habr.com/ru/post/1790983/


All Articles