我想把HTML从'OFF'& # 39;在# 39;使用onclick事件,就像切换一样

I want to change the HTML from 'OFF' to 'ON' with an onclick event much like a toggle

本文关键字:一样 使用 HTML OFF onclick 事件      更新时间:2023-09-26

我想将HTML从'OFF'更改为'ON '。我可以使用一些jQuery和。html来做到这一点,像这样:

HTML:

<div class="sample" onclick="run();"><p>OFF</p></div>
Jquery:

function run(){
  $('.sample p').html("ON");
}

然而,当我这样做时,我也想在另一个onclick事件上将其更改回'OFF'。我试过……If/else语句、变量和switch语句。似乎没有工作,有没有其他首选的方法来切换html?

使用我的谷歌搜索能力,结果没有运气。

你可以试试:

HTML:

<div class="sample"><p>OFF</p></div>

JS:

jQuery(function($) {
    $('.sample p').on('click', function() {
        $(this).html($(this).html() == 'ON' ? 'OFF' : 'ON');
    });
});

有了jQuery,就不需要给HTML标签添加onclick属性了

尝试设置单个点击处理程序来检查div内的值,然后根据该值将其更改为on或Off。

<div class="sample"><p>OFF</p></div>
<script>
    $(document).ready(function() { 
          run();
    });
    function run(){
      $('.sample').click(function() {
        if ($('.sample p').html() == "on")) {
              // Set to On
        } else {
             // Set to off
        }
    }
</script>

你可以这样做:

var p = $('.sample p');
p.html( p.html()=="ON" ? "OFF" : "ON" );

移动内联函数处理程序并将事件绑定到脚本文件或脚本标记中。

$('.sample').on('click' , function() {
    var $p = $('p', this);
    $p.text() === 'OFF' ? $p.text('ON') : $p.text('OFF');
});

检查小提琴

我建议远离内联事件处理:

$('.sample p').click(function(){
    $(this).text(function(i, t){
        return t === 'OFF' ? 'ON' : 'OFF';
    });
});

JS Fiddle demo.

如果你想使用命名函数,但是:

function run(){
    $('.sample p').text(function(i,t){
        return t === 'OFF' ? 'ON' : 'OFF';
    });
}

JS Fiddle demo.

扩展此函数,使其可用于其他元素:

<div class="sample" onclick="run(this);"><p>OFF</p></div>

和jQuery:

function run(el){
    var self = el.nodeType === 1 ? $(el) : el;
    self.find('p').text(function(i,t){
        return t === 'OFF' ? 'ON' : 'OFF';
    });
}

JS提琴演示

让我来帮你写代码:

jQuery:

$(document).ready(function() {
    $("div.sample").click(function() {
        if ($("p", $(this)).html() == "ON") {
            $("p", $(this)).html("OFF");
        } else {
            $("p", $(this)).html("ON");
        }
    });
});
HTML:

<div class="sample">
    <p>ON</p>
</div>

只是一个想法:

http://jsfiddle.net/Mr2Mk/3/

<input class="toggle" type="checkbox"/>
CSS

input.toggle:after {
    content: "OFF";
    margin-left: 1.5em;
}
input.toggle:checked:after {
    content: "ON";
}

加更多的糖,你可以把它变成这样:

http://dropthebit.com/15/iphone-like-ios5-toggle-buttons/