2017-12-17 2 views
0

누군가가 도와 줄 수 있습니까? 아니면 어떻게 할 수 있습니까? 나는 식료품 목록에 대한 간단한 HTML 코드가 있습니다기존 jQuery 버튼에 jQuery가 포함 된 버튼을 추가하십시오.

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Let's buy...</title>   
     <link rel="stylesheet" href="css/normalize.css"> 
     <link rel="stylesheet" href="css/main.css"> 
    </head> 

    <body> 
     <h2 class="title">My grocery list<span id="counter"></span> </h2> 
     <ul id="list-items"></ul> 
     <div id="newItemButton"><button href="#" id="showForm">new item</button></div> 
     <form id="newItemForm"> 
      <input type="text" id="itemDescription" placeholder="Add item..."/> 
      <input type="submit" id="addButton" value="add" />  
     </form> 
     <script 
     src="https://code.jquery.com/jquery-3.2.1.min.js" 
     integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" 
     crossorigin="anonymous"></script> 
     <!-- <script type="text/javascript" 
     src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> --> 
     <script type="text/javascript" src="js/javascript.js"></script> 
    </body> 
</html> 

을 그리고 사용자가 목록에 요소를 추가하고 오전 - 사용자가 항목을 추가 할 때, 해당 항목은 버튼을 제공합니다. 이제 버튼에 "append()"가있는 4 개의 버튼을 더 추가하려면 "item change"버튼을 누르고, 사용자 환경 설정에 따라 빨강, 초록, 오렌지 및 회색과 같은 항목의 색상을 변경하려면 각 버튼을 클릭해야합니다. 버튼을 추가하려고하는데 추가하지 않은 것 같습니다. 페이지에 표시되지 않습니다. 단지 버튼 하나만 추가하려고했습니다.

$(function() { 
 
    let $list, $newItemForm, $newItemButton; 
 
    let item = ''; 
 
    $list = $('ul'); 
 
    $newItemForm = $('#newItemForm'); 
 
    $newItemButton = $('#newItemButton'); 
 

 
    function updateCount() { 
 
     let items = $('li').length; 
 
     $('#counter').text(items); 
 
    } 
 
    updateCount(); 
 

 
    $newItemButton.show(); 
 
    $newItemForm.hide(); 
 
    $('#showForm').on('click', function() { 
 
     $newItemButton.hide(); 
 
     $newItemForm.show(); 
 
    }); 
 

 
    $newItemForm.on('submit', function(e) { 
 
     e.preventDefault(); 
 
     let text = $('input:text').val(); 
 
     $list.append('<li>' + text + '<button id="btn-change">change item</button><hr></li>'); 
 
     $('input:text').val(''); 
 
     updateCount();  
 
    });

이는 = '과정을 추가하는 버튼'입니다 : 여기에 ... 내 jQuery 코드입니다

$('#btn-change').one('click', function() { 
 
      let b = $('<input/>').attr({ 
 
       type: "button", 
 
       id: "hot", 
 
       value: 'hot' 
 
      }); 
 
      $("button").append(b); 
 
     });

답변

0

다른있다 여러 버튼과 같이 처리해야 할 사항, 인스턴스화 방법 이벤트 처리기 등을 제공합니다. 그러나 "내 새로운 입력이 나타나지 않는 이유"에 대한 대답에 불과합니다.

버튼 요소는 요소를 포함하고 입력해서는 안됩니다. 왜 그것이 의미가 없는지 알 수 있습니다. 따라서 그 이후에 유형 버튼의 새로운 입력을 만들고 그것에 추가하지 않으려면 .after을 사용하십시오. 이제 클릭 실제 우리가 우리가 this를 사용하고 ID로 우리의 버튼에 추가 할 수 있습니다에 추가 할 사람이 있다고 가정 btn-change

$('#btn-change').one('click', function() { 
    let b = $('<input/>').attr({ 
     type: "button", 
     id: "hot", 
     value: 'hot' 
    }); 
    $(this).after(b); 
}); 
다음

또 다른 옵션은 단순히 동일한 기능을 수행하는 다른 방법을 사용하고, 수행 똑같은 이름이지만 아마도 그 이름이 그 의도를 더욱 분명하게 만듭니다.

$('#btn-change').one('click', function() { 
    let b = $('<input/>').attr({ 
     type: "button", 
     id: "hot", 
     value: 'hot' 
    }); 
    b.insertAfter(this); 
}); 

이제 우리는 우리가 우리 따라서 우리는 우리의 이벤트 핸들러뿐만 아니라 동적으로 허용 할 필요가 동적으로 클릭하는 버튼을 추가 관찰, 버튼을 추가 할 수 있습니다, 그 버튼의 컨테이너에 첨부입니다 .

list-items은 우리 컨테이너이므로 첨부 해 보겠습니다.

$('#list-items').one('click', '#btn-change',function() { 
    let b = $('<input/>').attr({ 
     type: "button", 
     id: "hot", 
     value: 'hot' 
    }); 
    b.insertAfter(this); 
}); 

이제 이벤트 핸들러가 생겼으므로 중복 ID는 유효하지 않으므로 ID 대신 클래스를 사용하도록 수정합니다. 이제 우리는 길에서 몇 가지 설명을 가지고

$('#list-items').one('click', '.btn-change',function() { 
    let b = $('<input/>').attr({ 
     type: "button", 
     class: "hot", 
     value: 'hot' 
    }); 
    b.insertAfter(this); 
}); 

이 솔루션

$(function() { 
 
    let $list, $newItemForm, $newItemButton; 
 
    let item = ''; 
 
    $list = $('#list-items'); // use faster id 
 
    $newItemForm = $('#newItemForm'); 
 
    $newItemButton = $('#newItemButton'); 
 

 
    function updateCount() { 
 
    let items = $list.find('li').length; // get inside our list 
 
    $('#counter').text(items); 
 
    } 
 
    updateCount(); 
 

 
    $newItemButton.show(); 
 
    $newItemForm.hide(); 
 
    $newItemButton.on('click', function() { 
 
    $newItemButton.hide(); 
 
    $newItemForm.show(); 
 
    }); 
 

 
    function addButton(place, b) { 
 
    let bt = $('<input/>').attr({ 
 
     type: "button", 
 
     class: b + "button colorbutton", 
 
     value: b 
 
    }).data("colorclass", b + "thing"); 
 
    bt.insertAfter(place); 
 
    } 
 
    // perhaps change to button type not submit type? 
 
    $newItemForm.on('submit', function(e) { 
 
    e.preventDefault(); 
 
    let text = $('#itemDescription').val(); // use fast id 
 
    text = text=""?"new":text;//avoid empty text 
 
    $list.append('<li><span class="desc">' + text + '</span><button type="button" class="btn-change">change item</button><hr></li>'); 
 
    $('#itemDescription').val(''); 
 
    updateCount(); 
 
    }); 
 
    $('#list-items').on('click', '.colorbutton', function() { 
 
    $(this).parent().find('.desc') 
 
    .removeClass("hotthing greenthing orangething greything") 
 
    .addClass($(this).data("colorclass")); 
 
    }); 
 
    //Note the change here from discussion, still adds the buttons but more modular, disables button to avoid second click vs the .one, works for new items 
 
    $('#list-items').on('click', '.btn-change', function() { 
 
    $(this).prop("disabled", true); // only add once so disable it 
 
    // add the color buttons, matches classes in css 
 
    addButton(this, "hot"); 
 
    addButton(this, "green"); 
 
    addButton(this, "orange"); 
 
    addButton(this, "grey"); 
 
    }); 
 
});
.hotbutton { 
 
    color: red; 
 
} 
 

 
.greenbutton { 
 
    color: green; 
 
} 
 

 
.orangebutton { 
 
    color: orange; 
 
} 
 

 
.greybutton { 
 
    color: grey; 
 
} 
 

 
.hotthing { 
 
    background-color: red; 
 
} 
 

 
.greenthing { 
 
    background-color: green; 
 
} 
 

 
.orangething { 
 
    background-color: orange; 
 
} 
 

 
.greything { 
 
    background-color: grey; 
 
} 
 

 
#list-items { 
 
    border: solid lime 1px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<body> 
 
    <h2 class="title">My grocery list<span id="counter"></span> </h2> 
 
    <ul id="list-items"></ul> 
 
    <div id="newItemButton"><button type="button" id="showForm">new item</button></div> 
 
    <form id="newItemForm"> 
 
    <input type="text" id="itemDescription" placeholder="Add item..." /> 
 
    <input type="submit" id="addButton" value="add" /> 
 
    </form> 
 
</body>

0
을 수행 할 수 있습니다

당신이 다루고있는 문제는 당신이 이벤트를 발생하려고한다는 것입니다 동적 생성 요소에서. 이벤트를 첨부 할 때 # btn-change 요소가 페이지에로드되지 않았습니다. documentation을 기반으로 셀렉터를 추가 할 수 있습니다. 이벤트를 페이지의 안정된 요소에 첨부해야합니다. e.

그래서 코드가이

$("ul#list-items").one('click','#btn-change', function() { 
     let b = $('<input/>').attr({ 
      type: "button", 
      id: "hot", 
      value: 'hot' 
     }); 
     $("button").append(b); 
}); 

과 같을 것이다 또는 당신은 문법적으로 이벤트를 첨부 할 수 g UL 번호 목록 - 항목.

또한 같은 페이지에 여러 번 존재하는 요소 (예 : <button id='btn-change'></button>)에 대해 ID 대신 클래스를 사용하도록 제안합니다.이 ID는 페이지에서 고유해야합니다.

그래서 내가 제안 코드는

$newItemForm.on('submit', function(e) { 
    e.preventDefault(); 
    let text = $('input:text').val(); 
    $list.append('<li>' + text + '<button class="btn-change">change item</button><hr></li>'); 
     $('input:text').val(''); 
     updateCount();  
}); 

class='btn-change'

id='btn-change'을 변경하고

$('ul#list-items').one('click','.btn-change', function() { 
    let btnContainer = $("<div></div>").css("display","inline-block").attr({ 
     class: "btn-container" 
    }); 

    btnContainer.append(
     $('<input/>').attr({ 
      type: "button", 
      class: "hot", //use class instead of id in case you generate more than 1 element 
      value: 'hot' 
     }) 
    ).append(
     $('<input/>').attr({ 
      type: "button", 
      class: "green", //use class instead of id in case you generate more than 1 element 
      value: 'green' 
     }) 
    ).append(
     $('<input/>').attr({ 
      type: "button", 
      class: "grey", //use class instead of id in case you generate more than 1 elements 
      value: 'grey' 
     }) 
    ).append(
     $('<input/>').attr({ 
      type: "button", 
      class: "orange", //use class instead of id in case you generate more than 1 element 
      value: 'orange' 
     }) 
    ); 

    btnContainer.insertBefore(this); 
    $(this).hide();//or remove based on what you want to achieve 

}); 

여기 i를 BTN-변경 클릭 이벤트의 코드를 다음과 같을 것 .btn- 변경을 선택자로 사용하고 있으며 컨테이너 요소를 만들어 4 개를 보유하고 있습니다. 버튼을 누른 다음 .btn- 변경 버튼 앞에 네 개의 버튼 컨테이너를 추가하고 버튼을 숨 깁니다.

네 개의 버튼의 컨테이너를 제거/숨기고 나중에 .btn 변경 버튼을 표시하는 코드 부분을 추가 할 수 있습니다.

관련 문제