将span值存储到javascript变量中 [英] Storing a span value into a javascript variable

查看:130
本文介绍了将span值存储到javascript变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个javascript,它会经历一个跨度,获取它的值,并将其存储在一个变量,可以用于执行算术。

I am trying to write javascript that will go through a span, grab its value, and store it in a variable that can be used to perform arithmetic.

<span id ="Weekly" class="ServerData" data-tag="WeeklyCarSales">**30**</span>
<span id ="Monthly" class="ServerData" data-tag="DailyCarSales">**6**</span>

关于上述两行,我的函数如下。在这个电流设置我得不到结果。

Pertaining to the above two lines, my function is given below. In this current set up I get no result.

function divide(n1, n2) {
    ans = n1 / n2;
    document.write(" " + ans + "<BR>");
    return ans;
}
var a = $('#WeeklyCarSales').ServerData;
var b = $('#DailyCarSales').ServerData;
divide(a, b);



我应该得到一个5的答案,我知道实际的算术工作,如果我强制整数/浮点值到变量。我似乎有连续的麻烦锁定'30'和'6',这是跨度值。任何想法如何抓住这2个跨越价值?

I should be getting an answer of "5" yet get nothing. I know the actual arithmetic works if I force an integer/float value into the variables. I seem to have continuous trouble locking down the the '30' and '6', which are the span values. Any ideas on how to grab those 2 span values?

推荐答案

这应该可以做到...

This should do the trick...

function divide(n1, n2) {
    var ans = n1 / n2;
    document.write(" " + ans + "<BR>");
    return ans;
}

var a = parseInt($("#Weekly.ServerData").text().replace(/\*/gmi, ""), 10)
  , b = parseInt($("#Monthly.ServerData").text().replace(/\*/gmi, ""), 10);

divide(a, b);

这里是工作 JSFiddle

这篇关于将span值存储到javascript变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆