JQuery:在click函数中切换多个文本

时间:2013-07-09 20:24:43

标签: javascript jquery jquery-datatables

我有一个JQuery函数可以切换数据库中的列(根据datatables.net)

<a href="javascript:void(0);" onclick="fnShowHide([1]);" id="name">Show Name</a>

点击Show Name会隐藏列,但我还想将链接现在更改为Hide Name

有多个隐藏/显示列的链接,例如显示地址,显示公司等,它们都转到相同的fnShowHide函数。

JQuery切换在点击内嵌入不起作用。 (this).text也不起作用。 fnShowHide之外的单独切换功能将链接设置为display:none

function fnShowHide( iCol )
        {

2 个答案:

答案 0 :(得分:2)

尝试这种方式:

标记

<a href="javascript:void(0);" onclick="fnShowHide.call(this, [1]);" id="name">Show Name</a>

JS

function fnShowHide( iCol ) {
 //Your code
    $(this).text(function(_, text) { //now this refers to the element clicked
        return text === 'Show Name' ? 'Hide Name' : 'Show Name';
   });
}

<强> Fiddle

或使用jquery进行事件注册并删除元素上的内联onclick属性,使用data- *属性指定元素的相关数据并使用jquery数据api来获取它:

Makup

 <a href="javascript:void(0);" data-icol="[1]" id="name">Show Name</a>

JS

$(function(){
     $('#name').click(fnShowHide);
});

function fnShowHide()
{
     var iCol = $(this).data('icol'); //will give [1]
         //Your code
     $(this).text(function(_, text) { //now this refers to the element clicked
        return text === 'Show Name' ? 'Hide Name' : 'Show Name';
     });
}

<强> Demo

<强>更新

基于对多个字段的评论支持。

$(function () {
    $('.fields').click(fnShowHide);
});

var showregex = /^Show/i; //matches starting Show word
var hideregex = /^Hide/i; //matches starting Hide word

function fnShowHide() {

    var iCol = $(this).data('icol'); //will give [1]
    console.log(iCol);
    //Your code
    $(this).text(function (_, text) { //now this refers to the element clicked

    return showregex.test(text) ? //test if it Show
                 text.replace(showregex, 'Hide') : //replace it with hide
                 text.replace(hideregex, 'Show'); // else replace it with show

    });
}

<强> Fiddle

答案 1 :(得分:1)

您可以使用jQuery text方法显示所需的文本

function fnShowHide( iCol ) {

    $(this).text(function(i, txt) {
        return txt === 'Show Name' ? 'Hide Name' : 'Show Name';
   });
}

此外,最好删除inline个事件并将其分配到javascript文件中。

<强> HTML

<a href="javascript:void(0);" data-id="[1]" id="name">Show Name</a>

并使用数据 - * 属性来保存数字(如果有的话)。

<强>的Javascript

$('a').on('click', fnShowHide);

function fnShowHide() {
    var $this = $(this);
        iCol = $this.data('id');
    $this.text(function (i, txt) {
        return txt === 'Show Name' ? 'Hide Name' : 'Show Name';
    });
}

<强> Check Fiddle