每次点击按钮时都会将数字连接到url?

时间:2015-05-04 08:30:25

标签: javascript string numbers concatenation concat

每次点击按钮时,如何将数字连接到字符串? 如果我记录cConcate变量,您将看到第一个值是正确的,但在后续点击时,url拒绝更新。

var tNumber = 1;
var sSting = "http://www.test.com/";
var cConcate = sSting + tNumber
$("button").click(function(){
    tNumber++;
    console.log(cConcate);
    console.log(tNumber);
});

这是在线版本: http://codepen.io/vincentccw/pen/MwwRZG

3 个答案:

答案 0 :(得分:1)

在点击处理程序中进行连接,而不是仅执行一次:

var tNumber = 1;
var sString = "http://www.test.com/";
$("button").click(function(){
    var cConcate = sString + tNumber++;
    console.log(cConcate);
    console.log(tNumber);
});

答案 1 :(得分:1)

cConcate置于button click event内,因为它应该更新。 将您的代码更改为

var tNumber = 1;
var sSting = "http://www.test.com/";
var cConcate = sSting;
$("button").click(function(){
  tNumber++;
  cConcate= cConcate + tNumber;
  console.log(cConcate);
  console.log(tNumber);
});

或者如果您只想附加一个数字:

var tNumber = 1;
var sSting = "http://www.test.com/";
$("button").click(function(){
  tNumber++;
  var cConcate= sSting + tNumber;
  console.log(cConcate);
  console.log(tNumber);
});

答案 2 :(得分:1)

你可以这样做,

    var tNumber = 1;
    var sSting = "http://www.test.com/";

    $("button").click(function(){
        var cConcate = sSting + tNumber
        console.log(cConcate);
        console.log(tNumber);
        tNumber++;
    });