最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught TypeError: $(this).search is not a function - Stack Overflow

programmeradmin2浏览0评论

Uncaught TypeError: $(this).search is not a function

$(document).ready(function(){
    $('#caption').on('keypress', function () { 
            var n = $(this).search('#');
            if(n != "-1"){
                window.alert("There's a hash");
            }else{
                 window.alert("There's not a hash");
            }


    });
});

Uncaught TypeError: $(this).search is not a function

$(document).ready(function(){
    $('#caption').on('keypress', function () { 
            var n = $(this).search('#');
            if(n != "-1"){
                window.alert("There's a hash");
            }else{
                 window.alert("There's not a hash");
            }


    });
});
Share asked Jul 18, 2016 at 22:29 LinuxeLinuxe 131 gold badge1 silver badge3 bronze badges 2
  • What is #caption, and in what way are you searching for #? Is it the value, the HTML, or an attribute? – castletheperson Commented Jul 18, 2016 at 22:38
  • # is the value of textarea – Linuxe Commented Jul 18, 2016 at 22:42
Add a ment  | 

2 Answers 2

Reset to default 6

search is a JavaScript method for a string type.

So if you want to use search, your line var n = $(this).search('#'); should be changed to var n = $(this).val().search('#'); or var n = $(this).text().search('#'); depending on the tag of #caption element.

You can use indexof(), if you want search in your input the character #.

Remember, search() is used to regular expression. Otherwise indexOf() is going to be faster.

 $(document).ready(function(){
    $('#caption').on('keypress', function () { 
        var n = $(this).val();
        if(n.indexOf("#") > -1){
            window.alert("There's a hash");
        }else{
             window.alert("There's not a hash");
        }

   });
});

Result: https://jsfiddle/cmedina/3v04fvmb/

发布评论

评论列表(0)

  1. 暂无评论