未添加到购物清单的商品

时间:2014-08-16 18:34:54

标签: javascript jquery

我正在尝试建立一个购物清单网站,当用户在表单中输入内容时,会在其下方显示一个列表,类似于this website。我的JavaScript代码如下,而我的HTML和CSS位于jsfiddle

$(document).ready(function() {
    function addItem() {
        $(".typehere").keyup(function(event) {
            if (event.which == 13) {
                displayItem();
            }
        });
    }
    function displayItem() {
        var item = $(".typehere").val();
        var work = '<li><p>'+item+'</p><button>Completed</button><button>Remove</button></li>';
        $(".listed-items").prepend(work);
        $(".typehere").val('');
    }
});

1 个答案:

答案 0 :(得分:0)

您处理输入提交的代码不正确:

  • 事件处理程序包含未调用的addItem函数
  • 不会阻止对于sumbiting的默认行为
  • 挂在keyup上,而不是keydown(这对预防很重要)

至少应该是这样的:

$(document).ready(function()
{
    $(".typehere").keydown(function(event)
    {
        if (event.which == 13)
        {
            event.preventDefault();
            displayItem();
        }
    });

    function displayItem()
    {
        var item = $(".typehere").val();
        var work = '<li><p>' + item + '</p><button>Completed</button>      <button>Remove</button></li>';
        $(".listed-items").prepend(work);
        $(".typehere").val('');
    }
});

fiddle with this