Невозможно нацелить элементы, которые были добавлены после загрузки DOM с помощью $ (event.target). css - PullRequest
2 голосов
/ 19 февраля 2020

Проблема заключается во второй и третьей функциях в тегах скрипта. Я понимаю, что мне не нужны обе функции, однако я оставил их обе, потому что хотел показать разработчикам, просматривая мой код, разные решения, которые я пробовал. У меня проблема в том, что я не могу стилизовать event.target, если цель была добавлена ​​через функцию, которая имела место после загрузки DOM. Я пробовал использовать стандартные Javascript и jQuery, я предпочитаю jQuery, но приму ответ либо в стандартном Js, либо в jQuery. «Спасибо» всем, кто нашел время, чтобы посмотреть это. Я нашел еще 2 вопроса на эту тему, но они относятся к jQuery методам, которые давно устарели, и я не мог заставить их код работать (я думаю, что их ответы использовали метод делегата jQuery из jQuery v1 .7).

Хорошо, поэтому мне пришлось извлечь весь мой код CSS, Js & HTML из инфраструктуры CodeIgniter-3 MVC, а затем связать его вместе. Я потратил как минимум час, пытаясь упростить ее до проблемы root для всех, кто ее просматривает.

<!DOCTYPE html>
<html lang="en">

<head>
      <meta charset="utf-8">
      <meta author="AFT3RxL1F3">
      <!--
            AFT3RxL1F3: StyleSheet -->
      <style type="text/css">


@import url('https://fonts.googleapis.com/css?family=Clicker+Script|Open+Sans+Condensed:300|Righteous|Sofia|Sriracha|Ubuntu|Ubuntu+Condensed&display=swap');


 :root{
       --bg-page: #333;
       --title: #075;
       --pos: #0BB;
       --neg: #B00;
 }

 body{
       width: 100vw;
       margin: 0;
       padding: 0;
       background-color: var(--bg-page);
 }



 .foot{
       display: block;
       margin: 0;
       padding: 0;
       text-align: center;
       font-size: 14px;
       font-family: 'ubuntu' sans-serif;
       color: #FFF;
 }
 .title-xl{
       display: inline-block;
       margin: 2px;
       padding: 0;
       font-size: 48px;
       font-family: 'Sofia', cursive;
       color: var(--title);
 }
 .subtitle{
       display: inline-block;
       margin: 0;
       padding: 0;
       font-size: 34px;
       font-family: 'Sofia', cursive;
       font-family: 'Sriracha', cursive;
       color: #FFF;
 }



 /* Screen B Elements */
 #popup-ingr{
       display: block;
       position: fixed;
       width: 335px;
       height: 160px;
       margin: 7vh 45vw;
       padding: 16px;
       border: 4px solid #FFF;
       background-color: rgba(0, 0, 0, .92);
 }

 .hide{
       display: none !important;
 }



 /* User Interface*/
 .container{
       display: grid;
       grid-template-areas: 'title' 'list' 'ui';
       grid-gap: 0;
       width: 95vw;
       height: 75vh;
       margin: auto;
       padding: 0;
       background-color: #2196F3;
 }

 .container>div{
       font-family: 'Open Sans Condensed', sans-serif;
       color: #FF9;
       border: 1px solid #000;
 }

 .container-title { 
       grid-area: title; 
       height: 6vh;
       margin: 0;
       padding: 0;
       text-align: center;
       text-decoration: underline;
       font-size: 32px;
 }
 .container-list {
       grid-area: list;
       height: 50vh;
 }
 .container-ui { 
       grid-area: ui;
       height: 18vh;
 }




 /* Genral Classes & Element Specific*/
 /*Element: ol & li*/
 ol{
       margin: 1vh 1vw;
       list-style: numbers;
       max-height: 47vh;
       max-width: 33vw;
       border: 4px solid rgba(120, 120, 120, 0.333);
       background: rgba(150,150,150, 0.5);
       overflow: scroll;
 }
 li{

       width: fit-content;
       padding: 4px;
       text-decoration: none;
       font-size: 24px;
       font-weight: 500;
       font-family: 'Ubuntu', sans-serif;
       color: #C50;
 }

 /* Element: Button & input type="submit"*/
 button{
       display: inline-block;
       width: 110px;
       height: 40px;
       margin: 0;
       padding: 0;
       text-decoration: dashed;
       font-family: 'Ubuntu', sans-serif;
       font-size: 21px;
       font-weight: 500;
       border: 2px solid #FFA;
       border-radius: 12px;
       background-color: #222;
 }

 button.open{
       color: var(--pos);
 }

 button.close{
       color: var(--neg);
 }

 button.x{
       display: block;
       width: 37px;
       height: 37px;
       margin: -8px 0 24px -10px;
       padding: -4px;
       font-size: 30px;
       color: #FFF;
       font-family: 'Ubuntu' sans-serif;
 }

 .centertext{
       text-align: center;
 }

 .center-80w-10m{
       width: 80%;
       margin: 5%;

 }

 /* Input type text*/
 input[type="text"]{
       font-size: 28px;
       font-family: 'Ubuntu Condensed', sans-serif;
       font-weight: 500;
       color: #0DD;
       border: 2px solid #FFF;
       background: #222;
 }

      </style>
      <!--
            CDN: Font Awesome -->
      <script src="https://kit.fontawesome.com/3d9b68708a.js" crossorigin="anonymous">
      </script>
      <!--
            CDN: jQuery -->

      <title>RM Ceta v2.0</title>
</head>

<body>



      <!-- PAGE TITLE -->
      <h1 id="page-title" class="centertext">
            <span class="title-xl">
                  Kitchen Art:
            </span>
            <span class="subtitle">
                  Recipe Creation
            </span>
      </h1>
      <br>



      <!-- HIDDEN SCREEN -->
      <div id="popup-ingr" class="hide">

            <button id="btn-popup-ingr-x" class="x">X</button>
            <div class="center-80w-10m">
                  <input id="ingreadiant" type="text">
                  <br>
                  <br>
                  <button id="btn02-add" class="open">+ ADD</button>
                  <button id="btn-popup-ingr-del" class="close">- DEL</button>
            </div>
      </div>



            <!-- ~~~~~~~~~3-PART GRID~~~~~~~~~
~~~~~~~~~ 1) Title ||      2) List  ||       3) UI  ~~~~~~~~~-->
      <div class="container">


<!--  (#1)    ::    Title     ~~~~-->
            <div class="container-title">
                  INGREADIANTS
            </div>



<!--  (#2)    ::    List      ~~~~-->
            <div class="container-list">
                  <ol id="ol-a" style="color: #FFF">
                        <li id="list_1">1</li>
                        <li id="list_2">2</li>
                        <li id="list_3">3</li>
                        <li id="list_4">4</li>
                        <li id="list_5">5</li>
                        <li id="list_6">6</li>
                        <li id="list_7">7</li>
                        <li id="list_8">8</li>
                        <li id="list_9">9</li>
                  </ol>
            </div>




<!--  (#3)    ::    UI   ~~~~-->
            <div class="container-ui">
                  <button id="abc" class="open">+ ADD</button>
                  <button id="btn-del" class="close">- DEL</button>


                  <button id="btn-test-a" class="close">TEST: A</button>
                  <button id="btn-test-b" class="close">TEST: B</button>
                  <button id="btn-test-c" class="close">TEST: C</button>
            </div>
      </div>
<!-- !!! end of 3-part grid  -->




<!-- FOOTER -->
      <hr>
      <p class="foot">Designed Developed and Writen By: AFT3RxL1F3</p>



      <script src="https://code.jquery.com/jquery-3.4.1.js"
            integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
      <script src="rm.js"></script>
</body>

</html>
      <script>
//Document -&- Window EventListeners and their function code

window.onclick = e => {
      console.log(e.target);
      console.log(e.target.tagName);
  } 

   $('li').click(function(event){
       console.log('Test: ');
        console.log(event.target);
        $('li').css('background', '#000');
        $(event.target).css("background-color", "yellow");
   });

   $('li').on('click', function(event){
      console.log('Test: ');
       console.log(event.target);
       $('li').css('background', '#000');
       $(event.target).css("background-color", "yellow");
   });









//                            ~*~*~*~ ~*~*~*~ CLASS: LIST ~*~*~*~ ~*~*~*~  
class List {

      constructor() {
            this.list = new Array();
            this.listCopy = new Array();

      }//f(!)

      listSize(){
            return this.list.length;
      }

      display(id) {

            let x = list.list.length;
            let i = 0;
            $(id).html('');

            for (let i = 0; i < x; i++) {
                  $(id).append('<li style="background: #000">' + list.list[i] + '</li>');
            }

      }//f(!)

      add(ingr){
            console.log($('#ingreadiant').val());
            this.list.push(ingr);
            this.display("#ol-a");
      }

      delete(index){
            for(let i = 0; i < this.listSize(); i++){
                  console.log(i);
                  console.log(this.list[i]);
            }
      }
}//                                                               ~*~*~*~ end of Class: List  ~*~*~*~












//TESTING CODE, Elemz &EVT Listeners
list = new List();

$('#btn-test-a').click(function () {
      console.log('TEST: A');
      list.display('#ol-a');
});

$('#btn-test-b').click(function () {
      console.log('TEST: B');
      list.add();
});

$('#btn-test-c').click(function () {
      console.log('TEST: C');
      let ingreadiant = $('#input-ingr')
      list.add('#ol-a', ingr);
});

// Beta Permenant Buttons, their EVT-Listeners & their F()'s

$('#abc').click(function(){
      $('#popup-ingr').removeClass('hide');
});


$('#btn-popup-ingr-x').click(function(){
      $('#popup-ingr').addClass('hide');
});

$('#btn-popup-ingr-add').click(function(){
      list.add();
});

$('#btn02-add').click(function(){
      let ingr = $('#ingreadiant').val();
      list.add(ingr);
})
      </script>
</body>

</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...