简体   繁体   English

谁能告诉我为什么我的JavaScript点击无法正常工作?

[英]can anyone tell me why my javascript clicks isnt working?

i am making a shopping cart, looking to change the quantities but cant work out why its not working. 我正在制作购物车,希望更改数量,但无法弄清为什么它不起作用。 i have created two funtions, one to add quantities and one to take away. 我创建了两个功能,一个增加数量,另一个带走。 i want to apply this to multiple objects in my shopping cart. 我想将此应用到购物车中的多个对象。 it works if i change the p tag to an id rather than a class but i want it to apply to multiple items 如果我将p标签更改为一个id而不是一个类,它将起作用,但是我希望它应用于多个项目

<div class="controlpic">
  <img class="img" src="jsbook1.png">
  <button onClick="onClick2()">-</button>
  <p class="clicks">0</p>
  <button onClick="onClick()">+</button>
  <button class="addBasket">Add to Basket</button>
  <div>some text about this product</div>
</div>
/* onclick function will add clicks for basket*/
var clicks1 = 0;

function onClick() {
    clicks1 += 1;
    document.getElementsByClassName("clicks").innerHTML = clicks1;
  }
  /* onclick function will take away clicks for basket*/
var clicks1 = 0;

function onClick2() {
  if (clicks1 > 0) {
    clicks1 -= 1;
    document.getElementsByClassName("clicks").innerHTML = clicks1;
  }
}

The problem 问题

The problem in your code is that getElementsByClassName returns an HTMLCollection , which is similar to (but not the same as) an array. 您的代码中的问题是getElementsByClassName返回一个HTMLCollection ,它类似于(但不等同于)数组。

Instead of changing the innerHTML of your HTMLCollection , you should change the innerHTML the element(s) in your HTMLCollection . 而不是更改HTMLCollectioninnerHTML ,您应该更改innerHTML HTMLCollection中的HTMLCollection


The solution 解决方案

If you only have one element with the class "clicks", you can just replace ... 如果您只有一个元素属于“ clicks”类,则可以替换...

document.getElementsByClassName("clicks").innerHTML = clicks1;

... with ... ...与...

document.getElementsByClassName("clicks")[0].innerHTML = clicks1;

... and everything will work just fine. ...一切都会正常进行。

If you need to support multiple elements, you'll have to loop over those elements : 如果需要支持多个元素,则必须遍历这些元素:

[].forEach.call(document.getElementsByClassName('clicks'), function(clicks) {
    clicks.textContent = clicks1;
});

A demo 演示

 var clicks1 = 0; function onClick() { clicks1 += 1; [].forEach.call(document.getElementsByClassName('clicks'), function(clicks) { clicks.textContent = clicks1; }); } function onClick2() { if (clicks1 > 0) { clicks1 -= 1; [].forEach.call(document.getElementsByClassName('clicks'), function(clicks) { clicks.textContent = clicks1; }); } } 
 <div class="controlpic"> <img class="img" src="jsbook1.png"> <button onClick="onClick2()">-</button> <p class="clicks">0</p> <button onClick="onClick()">+</button> <button class="addBasket">Add to Basket</button> <div>some text about this product</div> </div> 

Your problem 你的问题

it works if i change the p tag to an id rather than a class but i want it to apply to multiple items 如果我将p标签更改为一个id而不是一个类,它将起作用,但是我希望它应用于多个项目

Your approach 你的方法

It doesn't work, because you are trying to set property innerHTML on an HTMLCollection that document.getElementsByClassName("clicks") returns, instead of setting it on every of those elements. 这是行不通的,因为您尝试在document.getElementsByClassName("clicks")返回的HTMLCollection上设置属性innerHTML ,而不是在所有这些元素上进行设置。

Fix 固定

Replace your document.getElementsByClassName("clicks").innerHTML = clicks1 with: 将您的document.getElementsByClassName("clicks").innerHTML = clicks1为:

[].forEach.call(document.getElementsByClassName('clicks'), function(element) {
  element.textContent = clicks1;
});

Demo 演示版

Below demo contains many flaws, it only presents how to implement the above fix. 下面的演示包含许多缺陷,仅介绍如何实现上述修复。 Also, each quantity modifier ( + or - ) will update all counters. 同样,每个数量修饰符( +- )将更新所有计数器。 For solution to this, see section Rewrite . 有关此问题的解决方案,请参见“ 重写”部分。

 /* onclick function will add clicks for basket*/ var clicks1 = 0; function onClick() { clicks1 += 1; [].forEach.call(document.getElementsByClassName('clicks'), function(element) { element.textContent = clicks1; }); } /* onclick function will take away clicks for basket*/ var clicks1 = 0; function onClick2() { if (clicks1 > 0) { clicks1 -= 1; [].forEach.call(document.getElementsByClassName('clicks'), function(element) { element.textContent = clicks1; }); } } 
 <div class="controlpic"> <img class="img" src="jsbook1.png"> <button onClick="onClick2()">-</button> <p class="clicks">0</p> <button onClick="onClick()">+</button> <button class="addBasket">Add to Basket</button> <div>some text about this product</div> </div> 

Comments 评论

Few other notes about your code: 关于您的代码的其他几点注意事项:

  • Don't use inline onclick use element.addEventListener('click', someFunction) 不要使用内联onclick使用element.addEventListener('click', someFunction)
  • Rather than innerHTML in your case, you can use textContent . 您可以使用textContent ,而不是用innerHTML It's safer and faster. 更安全,更快捷。
  • Defining var clicks1 = 0 second time makes no difference in your code. 第二次定义var clicks1 = 0不会对您的代码造成任何影响。

Rewrite 改写

 function setQuantityModifier(element) { 'use strict'; var quantity = element.parentNode.getElementsByClassName('clicks')[0]; element.addEventListener('click', function() { 'use strict'; if (element.value === '+') { quantity.textContent = parseInt(quantity.textContent) + 1; } else if (parseInt(quantity.textContent) > 0) { quantity.textContent = parseInt(quantity.textContent) - 1; } }); } [].forEach.call(document.querySelectorAll('.controlpic > input'), setQuantityModifier); 
 <div class="controlpic"> <img class="img" alt="ADDME" src="jsbook1.png"/> <input type="button" value="&ndash;"/> <p class="clicks">0</p> <input type="button" value="+"/> <button class="addBasket">Add to Basket</button> <div>some text about this product</div> </div> <div class="controlpic"> <img class="img" alt="ADDME" src="jsbook2.png"/> <input type="button" value="&ndash;"/> <p class="clicks">0</p> <input type="button" value="+"/> <button class="addBasket">Add to Basket</button> <div>some text about this product</div> </div> 

It doesn't work because document.getElementsByClassName returns an array (as you see getElement s , which is plural). 它不起作用,因为document.getElementsByClassName返回一个数组(如您所见,getElement s是复数)。 You can either do document.getElementsByClassName('clicks')[0].innerHTML or you can use document.querySelector('.clicks').innerHTML 您可以执行document.getElementsByClassName('clicks')[0].innerHTML ,也可以使用document.querySelector('.clicks').innerHTML

EDIT: for updating multiple elements with class name, you can use (based on @tymeJV's comment): 编辑:使用类名更新多个元素,您可以使用(基于@tymeJV的注释):

var clicks = document.getElementsByClassName('clicks');
for(var i = 0; i < clicks.length; ++i) {
    clicks[i].innerHTML = "...";
}

I personally like using document.querySelectorAll('.clicks') for any matchings (whether it is a class, id, or attribute). 我个人喜欢将document.querySelectorAll('.clicks')用于任何匹配项(无论是类,id还是属性)。

This should work for you: https://jsfiddle.net/DIRTY_SMITH/7oe5kh9L/30/ 这应该为您工作: https : //jsfiddle.net/DIRTY_SMITH/7oe5kh9L/30/

Add an id to <p class="clicks" id="clicks">0</p> <p class="clicks" id="clicks">0</p>添加ID

And insert text with document.getElementById('clicks').innerHTML = clicks1; 并使用document.getElementById('clicks').innerHTML = clicks1;插入文本document.getElementById('clicks').innerHTML = clicks1;

Also remove the second var clicks1 = 0; 同时删除第二个var clicks1 = 0; because you only need to declare a variable once. 因为您只需要声明一次变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有人能告诉我为什么我的 js 计时器不工作吗? - Can someone tell me why my js timer isnt working? 谁能告诉我为什么我的Scrollspy无法正常工作? - Can anyone tell me why my Scrollspy is not working? 谁能告诉我为什么我的最后2个如果其他语句不起作用? 全新的JavaScript在这里 - Can anyone tell me why my last 2 if else statements are not working? Brand new to JavaScript here 谁能告诉我为什么这一次有效? - Can anyone tell me why this is working once? 谁能告诉我为什么这个javascript函数调用不起作用? - Can anyone tell me why this javascript function call isn't working? 当我将 animation 效果包装在 function 中时,它停止工作。 谁能告诉我为什么? - When I wrap my animation effect in a function, it stops working. Can anyone tell me why? Javascript初学者-谁能告诉我为什么我的按钮不起作用? - Javascript beginner - Can anyone tell me why my button doesn't work? 谁能告诉我为什么我的投影透视矩阵不起作用? - Can anyone tell me why my projection perspective matrix isn't working? 谁能告诉我为什么这个循环无法正常工作? - Can anyone tell me why this loop isn't working as it should? 谁能告诉我为什么在不处理样式组件之前? - Can anyone tell me why before not working on styled components?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM