【问题标题】:Changing the value of a boolean (Jquery/Javascript)更改布尔值 (Jquery/Javascript)
【发布时间】:2012-12-30 01:05:13
【问题描述】:

我正在尝试通过使用函数对此值进行布尔更改。我是这样尝试的:

var itemInStock = false;

$("#button").click(function(){
    itemInStock = true
}
if( itemInStock === false){
    document.write("item is out of stock");
} else{
    document.write("item is in stock");
}

我明白为什么它不起作用,但我找不到解决这个问题的方法!

【问题讨论】:

  • 您不能在加载后使用 document.write,也不需要在单击按钮时而不是之前更改布尔值
  • 那总是写item is out of stock
  • 您可能希望切换状态,而不是盲目设置。可能是。目前还不清楚您要做什么。
  • 不要在标题中添加“SOLVED”。改为接受答案。

标签: javascript jquery function boolean


【解决方案1】:

因为在单击按钮之前 itemInStock 不会改变...

【讨论】:

  • 但是我该如何解决这个问题,所以当我点击按钮时它会显示“商品有货”(例如)?
  • 您需要将该警报放在按钮处理程序中。
【解决方案2】:

您不能在加载后使用 document.write,而且在单击按钮时而不是之前的布尔值更改也不是必需的

创建一个 id="status" 的 span 并拥有

var itemInStock = false;
$(function() {  
  $("#button").click(function(){
    itemInStock = true;

    $("#status").html("item is in stock":
  }

  $("#status").html(itemInStock?"item is in stock":"item is out ofstock");
});

【讨论】:

    【解决方案3】:

    我只能猜到你想要达到的目标。似乎您想在某个时候检查该物品当前是否有库存。由于您无法知道点击何时发生,因此一种解决方案可能是定期检查该值。

    (function () {
        var itemInStock = false;
    
        $("#button").click(function () {
            itemInStock = true
        });
    
        window.setInterval(function () {
    
            if (itemInStock === false) {
                console.log("item is out of stock");
            } else {
                console.log("item is in stock");
            }
    
        }, 500);
    })()
    

    http://jsfiddle.net/Ttu5N/

    如果我的猜测有误,请告诉我。

    更新:更简单的方法

    $(function () {
        var $state = $('#state');
    
    
      $state.text('item is out of stock');
    
        $("#button").click(function () {
            $state.text('item is in stock');
        });
    
    
    })
    
    <button id="button">click me</button>
    <div id="state"></div>
    

    http://jsfiddle.net/Wb3ET/ 直接点击即可。

    【讨论】:

    • 太棒了!谢谢!这正是我正在寻找的!
    【解决方案4】:
    // HTML
    <div id="status">item is out of stock by default</div>
    
    // JS
    var itemInStock = false;
    
    $("#button").click(function(){
        itemInStock = true;
    }, changeStatus());
    
    function changeStatus(){
        if( itemInStock === false){
             $('#status').html("item is out of stock");
        } else{
             $('#status').html("item is in stock");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-28
      • 2021-08-03
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多