Why all identifiers will not be changed, although I selected all of them using # idname?

I am completely new to coding in general. I started with the very foundations of HTML, CSS and JavaScript.

I have two paragraphs:

<p id="title1">Change this</p>
<p id="title1"> Change this too! </p>

While the first automatically changes:

<script type="text/JavaScript">
    $('#title1').html('Changed!');
</script>

second no. But right? Since everyone is #title1changing?

I have the same problem for the version onclick. The first paragraph changes when you click on it, the second - no.

<p id="title3" onclick="sayGoodbye();">Toggle this Hello - Goodbye</p>
<p id="title3" onclick="sayGoodbye();">Thing to click on</p>
<script type="text/javascript">
    function sayGoodbye(){
        $("#title3").html('Goodbye');
        $("#title3").click(function(){
            $("#title3").html("Hello again!");
            $("#title3").off("click");
        });
    }
</script>
+4
source share
3 answers

, , ! !

"-", " ".

$(".title1").html("Changed!");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="title1">Change this</p>
<p class="title1"> Change this too! </p>
+3

HTML. class .

+2
  • id , , .
  • class .click() $(this), , .
  • If you want to call a function using an attribute onclick, pass the element with the key pressed this, for example onclick="sayGoodbye(this);".

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="title3" onclick="sayGoodbye(this);">Toggle this Hello - Goodbye</p>
<p class="title3" onclick="sayGoodbye(this);">Thing to click on</p>

<script type="text/javascript">
    function sayGoodbye(t){
        $(t).html('Goodbye');
        $(t).click(function(){
            $(this).html("Hello again!");
            $(this).off("click");
        });
    }
</script>
Run code
+2
source

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


All Articles