简体   繁体   English

在 html 中搜索 javascript 不起作用

[英]Search for javascript in html does not work

I want to display the search in the site header in the tpl file我想在 tpl 文件的站点标题中显示搜索


<div  class="search-widget" >

<form method="get" action="art/search">

<input type="text"  id="artnum" value="" maxlength="40" placeholder="" > 


<button type="submit"  onclick="TDMArtSearch()">
<i class="material-icons search">&#xE8B6;</i>
 <span class="hidden-xl-down"></span>
        </button>
</form>
<div class="tclear"></div>

<script type="text/javascript">

function TDMArtSearch(){
    var art = $('#artnum').val();
    if(art!=''){
        art = art.replace(/[^a-zA-Z0-9.-]+/g, '');
        location = '/art/search/'+art+'/';
    }
}
$('#artnum').keypress(function (e){
  if(e.which == 13){ TDMArtSearch(); return false;}
});
</script

        ></button>
    </form>
</div>

Search does not work.搜索不起作用。 If I delete form method="get" action="art/search" .如果我删除form method="get" action="art/search" Then search works.然后搜索工作。 Only works if you click on the search button.仅当您单击搜索按钮时才有效。 How to apply the form method to start searching with the enter key如何应用form method用回车键开始搜索

Just make the form executes the javascript function on submit:只需让表单在提交时执行 javascript 函数:

<div  class="search-widget" >

<form method="get" action="art/search" onsubmit="TDMArtSearch(); return false;">

<input type="text"  id="artnum" value="" maxlength="40" placeholder="" > 

<button type="submit"  onclick="TDMArtSearch()">
<i class="material-icons search">&#xE8B6;</i>
 <span class="hidden-xl-down"></span>
        </button>
</form>
<div class="tclear"></div>

<script type="text/javascript">

function TDMArtSearch(){
    var art = $('#artnum').val();
    if(art!=''){
        art = art.replace(/[^a-zA-Z0-9.-]+/g, '');
        location = '/art/search/'+art+'/';
    }
}
</script

        ></button>
    </form>
</div>

onsubmit attribute is to execute javascript when form is submited and return false is to stop "normal" submission. onsubmit 属性是在提交表单时执行 javascript,返回 false 是停止“正常”提交。 There are better ways to do this by adding listeners and having cleaner HTML code, but you can look for that once you know how this works.通过添加侦听器和使用更清晰的 HTML 代码,有更好的方法可以做到这一点,但是一旦您知道它是如何工作的,您就可以寻找它。

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

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