2014-12-08 2 views
0

자바 스크립트에서 문제를 해결하려고하고 있는데 jQuery가 아닌 자바 스크립트에서 처리하려고합니다. 자바 스크립트로 객체를 만들고이를 요소로 표시하고 eventListener를 바인딩합니다. 간단하게 이름, 설명 및 가격으로 객체를 만듭니다. 내가 기본적으로 원하는 것은 사람들이 해당 가격이 경고되는 이름을 클릭 할 때입니다. 자바 스크립트로 이것을 할 수있는 방법이 있습니까? 내 실제 프로젝트에서 사람들이 도구 설명과 같은 제품 설명을 볼 수 있도록 마우스를 가져 가야하지만 아이디어는 같습니다.jQuery가 아닌 javascript의 click 이벤트에서 특정 클래스의 다음 요소를 찾는 방법은 무엇입니까?

미리 감사드립니다. 여기

바이올린 : fiddle

그리고 몇 가지 코드 :

function getNextElement(elem, className) { 
    var next = elem.nextElementSibling; // set next element to "nextElementSibling" relative to passed element. 
    while (next && !next.classList.contains(className)) { // check for existence and class 
     next = next.nextElementSibling; // if it exists, but the class does not, move to the next element and repeat. 
    } 
    return next; // return whatever was found, or null 
} 
function showPrice() { 
    var elem = getNextElement(this, 'price'), 
     price = elem ? elem.innerHTML : 'Price not found.'; 
    alert(price); 
} 

업데이트 참조 :

function makeProduct (name, description, price) { 
    this.name = "<p class='name'>" + name + "</p>"; 
    this.description = "<p class='description'>" + description + "<p>"; 
    this.price = "<p class='price'>" + price + "</p>"; 
    document.getElementById('productlist').innerHTML+=this.name; 
    document.getElementById('productlist').innerHTML+=this.description;  
    document.getElementById('productlist').innerHTML+=this.price;  
} 

var product1=new makeProduct("Pizza", "very Tasty", 5.00); 
var product2=new makeProduct("Choclate milk", "warm for the cold winter", 3.00); 


var productnames = document.getElementsByClassName('name'); 
for (i=0; i<productnames.length; i++){ 
     (function(){ 
    productnames[i].addEventListener('click', showPrice, false); 
    })(); 
} 

function showPrice() { 
alert("product price"); 
} 

답변

2

빠른 수정이 일치하는 다음에게 p ELEM를 반환하는 함수를 작성하는 것입니다 바이올린 : http://jsfiddle.net/zkbdy0rt/5/

이렇게하는 더 좋은 방법은 제품 목록을 작성하는 방법을 변경하는 것입니다. 예를 들어, 각 제품을 div (class="product")을 포함하는 스타일로 쉽게 배치하거나 찾을 수 있습니다.

JavaScript에서는 DOM 요소에 임의의 속성을 추가하여 유용하게 사용할 수 있습니다. 예를 들어 DOM 요소에 가격을 저장 한 다음 클릭 이벤트 핸들러에서 값을 검색 할 수 있습니다.

div.price = product.price; 

다음 나중에 ...

showPrice = function (e) { 
    var price = this.parentElement.price; 
    alert(price.toFixed(2)); 
} 

작업, 예를 들어,이 바이올린을 참조하십시오

function makeProduct (name, description, price) { 
    this.name = "<p class='name'>" + name + "</p>"; 
    this.description = "<p class='description'>" + description + "<p>"; //this line 
    ... 
} 

//이 : http://jsfiddle.net/zkbdy0rt/6/

+0

와우, 고마워! 네, 첫 번째 대답은 제가 찾고있는 것입니다. 나는 자바 스크립트에서 객체 지향 코딩에 익숙하지 않고 모든 기능과 아웃을 아직 모른다. 그리고 나는 당신과 동의합니다 : 당신의 제안은 제보다 낫고 깨끗합니다.하지만 전에 제가 말씀 드렸듯이 저는 대부분 여기 배우려고합니다.) ... – Michelangelo

1

먼저 나는 당신의 현재 코드를 수정 회선 번호 :

두 번째로3210
this.description = "<p class='description'>" + description + "</p>"; //</p> should be closing tag 

는 :

function showPrice(evt) 
{ 
    var p1 = evt.target.nextSibling.nextSibling; 
    alert(p1.innerHTML);  
} 
:

function makeProduct (name, description, price) { 
//... 
document.getElementById('productlist').innerHTML+=this.price; 
} 

아무것도 반환 makeProduct(..)로, 선을 보일 것입니다 관련 가격을 returs product1 마지막으로

var product1=new makeProduct("Pizza", "very Tasty", 5.00); 

함수에 새로운 객체의 할당은있을 수 shoulding

DEMO

+0

감사합니다. 새로운 객체를 반환 할 때 변수에 넣는 것은 나쁜 습관입니까? 나는 많은 사람들이 그것을하는 것을 보았다.나는 당신이 무언가를 돌려주지 않더라도 다른 곳에서 당신의 물건에 접근하고 싶을 때 편리하다고 생각했다. – Michelangelo