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

javascript - If <li> contains specific text, return false - Stack Overflow

programmeradmin4浏览0评论

I have this HTML and I'm trying to return false on click if the element contains specific text.

This is my HTML:

<ul>
    <li id="1"></li>
    <li id="2"></li>
    <li id="3"></li>
    <li id="4"></li>
    <li id="5"></li>
    <li id="6">text</li>
    <li id="7"></li>
</ul>

Javascript:

$("ul").on('click', 'li', function (e) {
    var value = $(this).attr('id');
    if ("#" + value + ":contains(\"text\")"){  // Something similar to this
        return false;
    };
    alert('test');
});

How can I return false, if the element contains the word 'text'.

Example: / (this returns false on everything)

I have this HTML and I'm trying to return false on click if the element contains specific text.

This is my HTML:

<ul>
    <li id="1"></li>
    <li id="2"></li>
    <li id="3"></li>
    <li id="4"></li>
    <li id="5"></li>
    <li id="6">text</li>
    <li id="7"></li>
</ul>

Javascript:

$("ul").on('click', 'li', function (e) {
    var value = $(this).attr('id');
    if ("#" + value + ":contains(\"text\")"){  // Something similar to this
        return false;
    };
    alert('test');
});

How can I return false, if the element contains the word 'text'.

Example: http://jsfiddle/wSvLD/ (this returns false on everything)

Share Improve this question edited Dec 2, 2011 at 19:59 jQuerybeast asked Dec 2, 2011 at 19:05 jQuerybeastjQuerybeast 14.5k39 gold badges120 silver badges198 bronze badges 1
  • Please don't ever use jQuery's attr function. It's spaghetti code. Use this.id instead. – user1385191 Commented Dec 2, 2011 at 19:24
Add a ment  | 

4 Answers 4

Reset to default 1

You'll need to escape those quotes in contains("text")

Or use single quotes in bination with double quotes....

Also, the value var should be inside the event function.

EDITS:

$("li").click(function (e) {

    var value = $(this).attr('id');

    if ( $('#' + value + ':contains("text")').length != 0 ){ 
        return false;
    }

    alert('test');

});

:contains returns a jQuery object, so you need to check the length of the object to see if it contains a match.

http://jsfiddle/8NuvP/

You were pretty close!

$("ul").on('click', 'li', function (e) {
    if($(this).text() == "text"){
        return false;
    };
    alert('test')
});

Try this:

$('li:not(:contains(text))').click(function() {
    alert('test');
});
$("li").click(function(){
  $(this).text() == "text" ? return false: return "something else";
});

but if what you want to do is to use a click function on all BUT the one with "text", you should do this:

$('li:not(:contains("text"))').click(function(){ 
      //whatever you are trying to achieve
});
发布评论

评论列表(0)

  1. 暂无评论