简体   繁体   English

将DOM元素内容存储在变量中,并用它更新相同的DOM元素

[英]Store DOM element content in variable, and update the same DOM element with it

Given the following DOM element: 给定以下DOM元素:

<span class=itemNumber>10</span>

I want to store the number in a variable, transform it to an integer, add 1 to it, and then update it in the DOM. 我想将数字存储在变量中,将其转换为整数,向其添加1,然后在DOM中对其进行更新。

I tried to do it with this function, bound to a click event: 我尝试通过绑定到click事件的此功能进行操作:

var itemCount = parseInt($('.itemNumber').text())+1;
$('.itemNumber').html(itemCount);

Seems simple enough, but the result is not what I'm expecting. 看起来很简单,但是结果却不是我所期望的。 Instead of replacing the old "10" number with "11", it displays "1011". 而不是将旧的“ 10”数字替换为“ 11”,而是显示“ 1011”。 I tried using .empty() function before the .html(), but it's the same result. 我尝试在.html()之前使用.empty()函数,但结果相同。

I suspect the variable is not actually storing the number, but a reference to the element. 我怀疑变量实际上不是存储数字,而是对元素的引用。

Any ideas? 有任何想法吗?

Your code looks perfectly valid through. 您的代码看起来完全有效。 But this is a typical usage of text(func) syntax. 但这是text(func)语法的典型用法。

$('.itemNumber').click(function() {
    $(this).text(function (_, val) {
        return +val + 1;
    });
});

Demo 演示

Your issue could be that you have more than 1, .itemnumber and not using $(this) inthe handler could cause the selection of both. 您的问题可能是您拥有超过1个.itemnumber并且在处理程序中未使用$(this)可能导致两者都被选择。 and $('.itemNumber').text() will give you both the numbers together(innertext of both of them) say 1010 and it will increment it by 1 and you get the result as 1011 instead of 11 . $('.itemNumber').text()会将两个数字都在一起(两个数字都表示为1010 ,它将增加1 ,结果为1011而不是11

See the fiddle here http://jsfiddle.net/a4ry4/ 在这里查看小提琴http://jsfiddle.net/a4ry4/

So your fix would be to use the clicked instance alone in your handler to select the text. 因此,解决方法是仅在处理程序中使用clicked实例来选择文本。

var itemCount = parseInt($(this).text(), 10)+1;
$(this).html(itemCount);

The .text function can take a mutator function: .text函数可以使用mutator函数:

$('.itemNumber').text(function(_, txt) {
    return parseInt(txt, 10) + 1;
});

您可能需要先将itemCount转换为字符串,然后再将其用作项目的文本。

$('.itemNumber').text(itemCount.toString());

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

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