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