如何使用Jquery在2个替代字符串之间切换innerHTML

时间:2013-05-14 12:42:42

标签: jquery html

我有span元素,我想切换其他元素的'Price'和'Net',onclick之间的内容。

基本上,它需要测试现有的单元格内容以查看当前存在的内容,然后将其与另一个进行交换。

这样的事情:

<input
    type    = "checkbox"
    name    = "element1"
    onclick = "$(#element2).toggleHTML('Price', 'Net')">

<span id="element2">Price</span>

我编写了上面使用的toggleHTML方法来演示我期望它可能如何工作。

5 个答案:

答案 0 :(得分:8)

您可以使用htmltext方法的回调函数。

$('input[name="element1"]').click(function() {
    $('#element2').text(function(_, text) {
        return text === 'Price' ? 'Net' : 'Price';
    });
});

http://jsfiddle.net/BLPQJ/

您还可以定义一个简单的方法:

$.fn.toggleHTML = function(a, b) {
    return this.html(function(_, html) {
        return $.trim(html) === a ? b : a;
    });
}

用法:

$('#element2').toggleHTML('Price', 'Net');

http://jsfiddle.net/AyFvm/

答案 1 :(得分:1)

您可以这样做:

var html = $('#element2').html();
html = html.indexOf('Price') > -1 ? "Net" : "Price"; 
$('#element2').html(html)

答案 2 :(得分:1)

试试这个

HTML

<input
type    = "checkbox"
name    = "element1"
id="input1">

JQUERY

$('#input1').click(function(){
    $('#element2').text(function(){
      return $('#element2').text()=="Price" ?"Net":"Price" ; 
    });
}); 

避免使用内联javascript ...

fiddle here

答案 3 :(得分:0)

这是代码: html:

<input type = "checkbox" name = "element1" id="element1">

Javascript:

$(document).ready(function()
{
    $("#element1").click(function()
    {
        if($("#element2").html() == "Price")
            $("#element2").html("Net");
        else
            $("#element2").html("Price");
    });
});

答案 4 :(得分:0)

我有一个类似的问题,我的网页有多个&#39;阅读更多&#39;切换,假设改为“少阅读”。并在每次点击时再次返回。但它只适用于第一次迭代。其他人只切换一次然后停止,但链接仅适用于第一个。

代码:

$(".morelink_L3").click(function() {
  $(this).find("span").html($(".morelink_L3 span").html() == 'Read less' ? 'Read more' : 'Read less');
});

HTML:

<span class="moreLink morelink_L3" value="True">
     <span>Read more</span>
</span>