jQuery function execute on Button Click and Enter/Return (key)

后端 未结 3 1724
盖世英雄少女心
盖世英雄少女心 2021-02-08 23:54

I\'m trying to create a little search box that allows you to search Twitter based on the keyword you enter in the input field. While it\'s work, it only works if you press the S

相关标签:
3条回答
  • 2021-02-09 00:20

    EDIT: As Spudley suggested "one of the main points of using jQuery is to stop you having to use event triggers embedded in the HTML markup" so a better solution would be

    <script>
    $(document).ready(function(){
    
    function(data) {
    
    $('#twitterSearch').keydown(function(event){    
        if(event.keyCode==13){
           $('#startSearch').trigger('click');
        }
    });
    
    $('#startSearch').click(function(){ 
    
    $('#tweets .results').remove();
    
        var searchTerm = 'http://search.twitter.com/search.json?q=' + $('#twitterSearch').val() + '&callback=?'
    
        $.getJSON(searchTerm,  function(data) {
            $.each(data.results, function() {
                $('<div class="results"></div>')
                .hide()
                .append('<a class="userPicLink" href="http://twitter.com/' + this.from_user + '">'  + '<img class="userImg" src="' + this.profile_image_url + '">' + '</a>')
                .append('<span class="userName">' + '<a href="http://twitter.com/' + this.from_user + '">' + this.from_user + '</span>')
                .append('<span class="userText">' + this.text + '</span>')
                .append('<time class="textTime">' + relTime(this.created_at) + '</time>')
                .appendTo('#tweets')
                .fadeIn();
    
            });
    
      });
    
    </script>
    

    OR - Previous proposal:

    <input type="search" onkeydown="if(event.keyCode==13)$('#startSearch').trigger('click');" list="searchSugg" id="twitterSearch" placeholder="css3 animation" required aria-required="true"  >
    
    0 讨论(0)
  • 2021-02-09 00:36

    Try create listeners for both key press and mouse clicks.

    function myFunction(e){
        if (e.which=='13' || e.type=='click'){
            // Run your code here
        }
    }
    $(document)
      .on('click', '#startSearch', myFunction)
      .on('keypress', this, myFunction);
    

    In action http://codepen.io/scottyzen/pen/akWPJd

    0 讨论(0)
  • 2021-02-09 00:46

    If you want place event with not obtrusive js then you can use also this system:

    $("#element").keydown(function(event) {
    if (event.keyCode == 13) {
        // do stuff
    }
    

    also if you have a submit button, this is an alternative, #element must be the text field where you want catch the event.

    reference to this: answer

    0 讨论(0)
提交回复
热议问题