2016-08-05 4 views
1

다음 작업을 수행하는 작은 코드를 작성하려고합니다. 버튼을 여러 그룹으로 추가하고 버튼을 클릭하면 해당 div에 미리 정의 된 텍스트가 추가됩니다.버튼이있는 div에 사전 정의 된 html 추가

은 여기 예를 들어 내 코드를 넣어 :

<button id="hey-0">hey</button> 
<button id="hi-0">hi</button> 
<button id="hello-0">hello</button> 
<div id="text-0"></div> 

<button id="hey-1">hey</button> 
<button id="hi-1">hi</button> 
<button id="hello-1">hello</button> 
<div id="text-1"></div> 

<button id="hey-2">hey</button> 
<button id="hi-2">hi</button> 
<button id="hello-2">hello</button> 
<div id="text-2"></div> 

JAVASCRIPT에게 https://jsfiddle.net/kdpqu98p/3/

HTML I가 원하는,하지만 항상 텍스트를 추가하는 것처럼 거의 작동

$(document).ready(function() { 

    // Loops through all 3 groups 
    for (var i = 2; i >= 0; i--) { 
    // Gets the buttons and text block for this group. 
    var text = '#text-' + i; 
    var hey = '#hey-' + i; 
    var hi = '#hi-' + i; 
    var hello = '#hello-' + i; 

    // Add functions to the buttons. 
    $(hey).click(function(e) { 
     $(text).append('hey'); 
    }); 

    $(hi).click(function(e) { 
     $(text).append('hi'); 
    }); 

    $(hello).click(function(e) { 
     $(text).append('hello'); 
    }); 
    } 

}); 

첫 번째 div 및 버튼에 해당하는 div가 아닌 이유 때문입니다. Oo

여기 내 질문 사항은 다음과 같습니다. 오른쪽 버튼 찾기가 작동하지만 div가 아닌 이유 (모든 버튼이 작동하지만 항상 첫 번째 div에 텍스트가 추가되기 때문에). 그런 다음 더 쉽고 빠르게 할 수있는 방법이 있습니까? 나는 자바 스크립트와 jquery에 꽤 새로 워서 3 살짜리 말을해야합니다. 루프를 없애고 "모든 (#/word/-/index /) 버튼에 대해"같은 말을하는 함수 하나만 사용하여 html에/word /를 추가하도록 할 수 있습니다. # text-/index/div "라고 표시하지만 어떻게해야하는지 전혀 모른다.

답장을 보내 주셔서 감사합니다.

답변

4

DRY 원칙을 사용하여 코드를 크게 단순화 할 수 있습니다. 먼저 모든 button 요소에 공통 클래스를 넣고 value 특성을 사용하여 관련 값 div에 배치 할 값을 저장합니다. 거기에서 관련 클래스 div을 찾고 값을 추가하는 해당 클래스에 단일 이벤트 핸들러를 사용할 수 있습니다. 이 시도 :

그것은 내가 원하는 정확히 수행

$('.btn').click(function() { 
 
    $(this).nextAll('.text:first').append(this.value); 
 
});
div { 
 
    width: 300px; 
 
    height: 40px; 
 
    overflow-x: scroll; 
 
    margin-bottom: 10px; 
 
    background-color: #efefef; 
 
    border: 1px solid black; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button class="btn" value="hey-0">hey</button> 
 
<button class="btn" value="hi-0">hi</button> 
 
<button class="btn" value="hello-0">hello</button> 
 
<div class="text"></div> 
 

 
<button class="btn" value="hey-1">hey</button> 
 
<button class="btn" value="hi-1">hi</button> 
 
<button class="btn" value="hello-1">hello</button> 
 
<div class="text"></div> 
 

 
<button class="btn" value="hey-2">hey</button> 
 
<button class="btn" value="hi-2">hi</button> 
 
<button class="btn" value="hello-2">hello</button> 
 
<div class="text"></div>

+0

, 즉 최고입니다. 고마워요! :) – Kishlin

+0

문제 없습니다. 기꺼이 도와 드리겠습니다. –