繁体   English   中英

onClick事件不起作用-JS

[英]onClick event not working - JS

我正在编写一个非常简单的搜索功能,该功能将根据用户选择的内容从数据库中返回相似的结果,尽管在测试onClick函数时它不起作用,但我已经用类似的代码检查了我的代码,它应该可以工作,我在询问之前进行了搜索这个问题虽然对我来说没有解决方案,但这只是代码示例。

<form>
<fieldset>
    <legend>Search Form..</legend>
    <input type="text" id="itemID" name="itemName" placeholder="Enter item name.." />
    <select id="locSelect">
    <option id="loc1" value="mountain"> mountain </option>
    </select>
    </br>
    <input type="button" id="searchID" name="searchName" value="Search" onClick="runsearch();" />


</fieldset>
</form>

<div id="searchResult"></div>

<script type="text/javascript">

function runsearch()
{
    var item = $("#itemID").val();

    var location = document.getElementById("#locSelect");
    var selectedLoc = location.options[location.selectedIndex].text;

    if(item == '') 
    {
       alert("Item field is blank please specify an item");
    }

    else { $.post("LSR.php", {
        postitem = item,
        postlocation = selectedLoc },

        function(data)
        {
            $("#searchResult").html(data);
        });
    }
}
</script>

它应该接受用户选择的内容,并将其发送到与数据库进行比较的php页面,我为登录/注册页面编写了类似的代码,并且它起作用了,我不确定为什么这不起作用,唯一的原因选择,选项是不同的。我想了解我在做什么错。 感谢您的任何帮助。

您的函数中有语法错误。 用这个:

else { $.post("LSR.php", {
    postitem: item,
    postlocation: selectedLoc },

代替这个:

else { $.post("LSR.php", {
    postitem = item,
    postlocation = selectedLoc },

您还有另一个错误:

var location = document.getElementById("#locSelect");

应该:

var location = document.getElementById("locSelect");

并使用onClick将功能放在按钮之前。

这里有一个问题22,如果将函数放在窗体上方,则#itemID在DOM中尚不存在。 如果将函数放在表单下方,则函数runsearch尚不存在。

为什么不使用:

$(document).ready(function(){
    $(document).on("click", "#searchID", function(e){
        console.log("clicked!"); //watch console for this, delete this line once you know it works.
        runsearch();
    });
});

另外,您的代码有一些错误(包括另一个答案中提到的冒号/等号)。 我已经整理了一下。

这是错误的: document.getElementById("#locSelect");

如果您使用document.getElementById ,则不需要#。 那是一个jQuery id选择器。 但是,您正在使用jQuery,所以请接受它! jQuery中document.getElementById的等效项只是$("#IDOFELEMENT")

所有这个location.options[location.selectedIndex].text都可以缩写为: location.val() ,但是我总是使用$作为jQuery对象的前缀,因此很明显它们是jQuery对象,所以我重命名了变量$ location。

这是一个工作的小提琴:

http://jsfiddle.net/SeanKendle/b9udzjLp/

您需要先关闭<fieldset>标记,然后再关闭<form>标记,因为它们不正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM