将加号(+)改为条形(|)

Change plus ( + ) sign to bar ( | ) sign

本文关键字:      更新时间:2023-09-26

我只是想创建一些东西,当单击时会隐藏或显示项目下面的文本。我的问题是"当点击h1时,我如何将+符号更改为|符号。代码:

HTML:

<h1>+ Welcome</h1>
<p>This is the welcome greeting</p>

CSS:

p {
    display: none; 
}

JavaScript:

$( "h1" ).click(function() {
    if ($('p').is(':visible')){
        $('p').hide();              
    } else {
        $('p').show();      
    }
});

Js投标

由于单击的是h1,因此可以在函数中使用$(this)

$( "h1" ).click(function() {
    if ($('p').is(':visible')){
        $('p').hide();
        $(this).text('+ Welcome');
    } else {
        $('p').show();
        $(this).text('| Welcome');    
    }
});

DEMO

您应该将+放在一个元素中并更改它:

HTML

<h1><span>+</span> Welcome</h1>
<p>This is the welcome greeting</p>

jQuery

$( "h1" ).click(function() {
    if ($('p').is(':visible')){
        $('p').hide();
        $(this).find('span').text('+');
    } else {
        $('p').show();
        $(this).find('span').text('|');      
    }
});

jsFiddle演示

尝试使用::before伪元素:

<div class="wrapper">
    <h1>Welcome</h1>
    <p>This is the welcome greeting</p>
</div>
.wrapper > h1:before {
  content: '|';
}
.wrapper.hide > h1:before {
  content: '+';
}
.wrapper.hide > p {
    display: none;
}
$(".wrapper").addClass('hide').each(function() {
    var $wrapper = $(this);
    $wrapper.children('h1').on('click', function() {
        $wrapper.toggleClass('hide');
    });
});

演示

您可以使用.text()(doc):访问标签的内容

$( "h1" ).click(function() {
    if ($('p').is(':visible')){
        $('p').hide();
        $(this).text("+ Welcome");
    } else {
        $('p').show();
        $(this).text("| Welcome");
    }
});

然而,正如其他人指出的那样,如果将特殊字符移动到其自己的<span>元素中,这会更容易。还要考虑为要交互的元素指定一个id,因为$("p")将匹配页面中所有的p元素。

尝试将"+"放在自己的<span>标记中。

HTML:

<h1> <span id='symbol' class="plus">+</span> Welcome </h1>

jQuery:

$("h1").click(function(){
    var span = $("#symbol");
    if(span.hasClass("plus")){
        span.html("|");
        span.removeClass("plus");
        span.addClass("pipe");
    }else{
        span.html("+");
        span.removeClass("pipe");
        span.addClass("plus");
    }
});

希望它能有所帮助!

DEMO

这是你的代码

HTML

<h1><span>+</span> Welcome</h1>
<p>This is the welcome greeting</p>

JavaScript

$( "h1" ).click(function() {
    if ($('p').is(':visible')){
        $('p').hide();
        $(this).find('span').text('+');
    } else {
        $('p').show();      
        $(this).find('span').text('|');
    }
});

如果您不想更改标记,并且希望能够在不修改JavaScript的情况下灵活地更改h1中的其他文本,那么可以使用JavaScript替换函数。

$( "h1" ).on('click', function() {
    var heading = $(this).html();
    if ($('p').is(':visible')){
        $('p').hide();
        $(this).html(heading.replace('|', '+')); 
    } else {
        $('p').show();
        $(this).html(heading.replace('+', '|')); 
    }
});
相关文章:
  • 没有找到相关文章