Jquery :contains showing alert for all span

前端 未结 4 1246
旧时难觅i
旧时难觅i 2021-01-14 16:10

I have a span Text goes her like this

$(\'#contentarea\').bind(\'click\',function(e){
             


        
相关标签:
4条回答
  • 2021-01-14 16:12

    Try:

    var isBold =$(e.target).css('font-weight');
    if($(isBold === ("bold")|| isBold === 700){
                             alert('bold');
                        }
    

    This way you check for existence of CSS properties.

    0 讨论(0)
  • 2021-01-14 16:15

    you can use the attribute selector...(if you just need to select the span containing the style attribute as font..)

    try this

    $('span[style^="font-"]')
    

    this should select the span with style starting with font-

    or

    $('span[style="font-weight: bold;"]')
    

    fiddle

    0 讨论(0)
  • 2021-01-14 16:34

    First of all a heads up, the :contains() selector is for the content of the DOM node, so you could use it with the following HTML:

    <div id="contentarea">
        <span>Hello World</span>    // will alert when clicked
        <span>Goodbye World</span>  // will not alert when clicked
    </div>
    

    And the following jQuery:

    $('#contentarea').bind('click',function(e){
        e.preventDefault();
        if($(e.target).is('span')){
            if($(e.target).is(':contains(Hello)')){
                alert($(e.target).text());
            }
        }
    });
    

    What you're trying to do is look at the applied CSS styles, or an attribute, so you would want to do something more like this:

    HTML:

    <div id="contentarea">
        <span style="font-weight: bold;">Hello World</span>
        <span style="font-weight: 700;">Hello World</span>
        <span>Hello World</span>
    </div>
    

    jQuery:

    $('#contentarea').bind('click',function(e){
        e.preventDefault();
        if($(e.target).is('span')){
            if($(e.target).css('font-weight')==="bold" || $(e.target).css('font-weight')==="700"){
                alert($(e.target).text());
            }
        }
    });
    
    0 讨论(0)
  • 2021-01-14 16:37
    $(e.target).find(":contains(font-weight: bold;)")
    

    It always returns a jQuery collection of objects - including 0 length collection. This is not a javascript list and you always get true in boolean.

    var target = $(e.target);
    if(target.is('span')){
         if(target.css('font-weight') == 'bold'){
             alert('bold');
         }
    }
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题