简体   繁体   中英

Adding 1 to a css style property in Javascript

I am trying to first get the value of the order property of an element, and then adding 1 to it when I click a button. Thing is, instead of getting 1 and adding 1 and getting 2, I get 11. Shouldn't the "+=" operator add the values? What am I doing wrong?

carouselPrev.addEventListener("click", function(){

  const firstPost = document.querySelector(".blog-post");

  let firstPostOrder = firstPost.style.getPropertyValue('order');

  firstPost.style.order = firstPostOrder += 1;
});

Css properties are strings, and '1' + 1 = 11 .

Add "+" before firstPostOrder to convert it to a number.

firstPost.style.order = +firstPostOrder += 1;

值是字符串,因此它们是连接的,在使用parseInt()之前尝试解析为整数

Try this

carouselPrev.addEventListener("click", function(){

const firstPost = document.querySelector(".blog-post");

let firstPostOrder = firstPost.style.getPropertyValue('order');

firstPost.style.order = parseInt(firstPostOrder,10) +1;
});

No, the "+=" operator is an assignment operator you'd use in lieu of "=".

let x = 42;
x += 1;

is equivalent to

let x = 42;
x = x + 1;

You want to use just the "+" to add the values, not the "+=".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM