2015-11-01 38 views
0

我目前正在制作一个简单的基于web的计算器的过程。我无法将我的按钮的值分配到“屏幕”区域,我想要显示刚刚按下的数字的值。我可以将值变成一个javascript变量,但是当我尝试将它写入屏幕区域时,它总是以未定义的形式出现。使用jquery根据变量写div的html

这里是我的代码:

$(".numbers").click(function(){ 
    currentValue = ($(this).val()); 
    $("#screen").html(function(){ 
     return "<p> " + currentValue.toString() + "</p>"; 
    }) 
    }); 

这个问题似乎是代码得到运行两次,但只有当我有它设置为返回这个(如果我用回“测试”它完美)。

+1

尝试'$( “#屏”)HTML(函数(){ 回报 “

” + currentValue.toString()+ “

”; }())。'我猜测匿名函数需要执行才能返回所需的字符串! – Rayon

+0

or this:'$(“#screen”)。html(“

”+ currentValue +“

”);'(当你将数字连接到字符串时或者使用'.html() )。 – blex

+0

@blex,是的..有没有一个匿名函数作为参数.. – Rayon

回答

1

根据您所提供的代码,我相信这是所有你需要:

$(".numbers").click(function() { 
    currentValue = $(this).val(); 
    $("#screen").html("<p> " + currentValue + "</p>") 
}); 

我也相信,而不是使用.html(),你应该使用append()或使用输入框的屏幕和使用.val()。如何使用.html,每次按下数字时都会覆盖屏幕。您仍然可以使用.html()对于这一点,但你有新的按钮数以连接一部开拓创新的屏幕值:

$('#screen').html($('#screen').html() + currentValue); 

但最好使用.append()

$('#screen').append(currentValue); 

看一看这个FIDDLE那使用输入框:

<input type="text" id="screen"></input> 

<button class="numbers" value="1">1</button> 
<button class="numbers" value="2">2</button> 
<button class="numbers" value="3">3</button> 

$(".numbers").on('click', function() { 
    var $s = $('#screen'); 
    $s.val($s.val() + $(this).val()) 
}); 

每次按下一个号码时,它把它添加到当前串数字的末尾,inste覆盖一切的广告。

-1

看起来像你的代码工作,告诉我们你的HTML。

$(".numbers").on("click", function(){ 
 
    currentValue = $(this).val(); 
 
    $("#screen").html("<p> " + currentValue + "</p>"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<button class="numbers" value="2">Click me</button> 
 
<div id="screen"></div>

+0

使用代码片段编辑器在这里发布,而不是试图欺骗链接无代码到JSFiddle。 – mplungjan