使用 jQuery 在粗体和普通文本之间切换

Toggling between bold and normal text with jQuery

本文关键字:文本 之间 jQuery 使用      更新时间:2023-09-26

我目前正在通过Packtpub的Learning jQuery 4th Edition,尝试其中一个关于DOM操作的练习。

我正在尝试通过单击它来切换使div 加粗(通过添加元素而不是使用类或 css),并通过后续单击删除粗体。(即在粗体和普通文本之间切换)。

这就是我到目前为止想出的。

.HTML

//more html
<div id="f-author">by Edwin A. Abbott</div> <-- the div to be bolded
//more html

我的j查询

$(document).ready(function(){
    $('#f-author').click(function(){
      if($(this).contents().has('b')){
        $('this').find('b').contents().unwrap();
      }else{
        $(this).wrapInner('<b>');
      }
    });
});

当我单击div 时,我的代码中没有任何反应,我已经卡了几个小时,试图弄清楚到底出了什么问题。我的猜测是问题出在 if 条件上。

我试过将 if 条件替换为

if($(this).children().has('b'))

但似乎没有任何效果。

我希望有人指出我的错误。

谢谢!

您只需切换使用toggleClass添加粗体效果的特定类即可处理它。

Css类:

.bolder{
    font-weight:Bold;
}

法典:

$(document).ready(function(){
    $('#f-author').click(function(){
        $(this).toggleClass('bolder')
    });
});

演示:http://jsfiddle.net/IrvinDominin/LdE6g/

如果没有请求的类或 CSS,这将添加和删除 <b> 标记

$(document).ready(function () {
    $('#f-author').on('click', function () {
        if ($('b', this).length) {
            $( $('b', this).get(0).childNodes[0] ).unwrap();
        } else {
            $(this).wrapInner('<b></b>');
        }
    });
});

小提琴