JQuery hide() 后的 show()

3

HTML:

<table id="table1">
    <tr>
        <th>1</th>
        <th>2</th>
        <th>3</th>
    </tr>
    <tr>
        <td class="table1column1"><input type="text" id="idInput1" /></td>
        <td class="table1column2"><input type="text" id="idInput2" /></td>
        <td class="table1column3"><input type="text" id="idInput3" /></td>
        </tr>
</table>
<button>Hide-Text-Show</button>

JQuery:

$(document).ready(function() {
    $('button').click(function() {
        $('#idInput1').hide();
        $('.table1column1').text('Test');
        $('#idInput1').show();
    });
});

http://jsfiddle.net/QNxyG/

我不明白为什么在td元素中添加文本后,show()方法无法工作?谢谢。

1
以下答案是正确的,但是如果您将来想要自己找出发生了什么,我建议使用例如火狐浏览器中的Firebug或Chrome或IE中的开发者工具。 - Mario S
我最终选择了这个解决方案:http://jsfiddle.net/QNxyG/3/。 - user1889867
3个回答

4

http://jsfiddle.net/QNxyG/4/

使用.text()可以覆盖你示例中的任何内容...因此输入不再存在

HTML

<table id="table1">
    <tr>
        <th>1</th>
        <th>2</th>
        <th>3</th>
    </tr>
    <tr>
        <td class="table1column1"><span class="text" style="display:none;"></span><input type="text" id="idInput1" /></td>
        <td class="table1column2"><span class="text" style="display:none;"></span><input type="text" id="idInput2" /></td>
        <td class="table1column3"><span class="text" style="display:none;"></span><input type="text" id="idInput3" /></td>
    </tr>
</table>

<button>Hide-Text-Show</button>

jQuery

$(document).ready(function() {
    $('button').click(function() {
        var input = $('#idInput1');
        var text = input.parent('td').find('.text');
        text.text('text');
        text.toggle();
        input.toggle();
    });
});​

那么,我如何在td内切换(隐藏/显示)输入和文本?例如:第一次单击隐藏输入并显示文本,第二次单击显示输入并隐藏文本? - user1889867
看这里:http://jsfiddle.net/QNxyG/4/... 在一个空的 span 元素上加上 display none 和一个类名,然后使用 toggle() 代替 show 和 hide。 - Mik

4
因为使用`.text()`时,您会覆盖`#idInput1`元素(即它被删除了),所以下一个`$('#idInput1')`找不到要显示的元素。

0
$(document)
    .ready(function () {
    $('button')
        .click(function () {
        $('#idInput1')
            .hide(function () {
            $('.table1column1 input')
                .val('Test', function () {
                $('#idInput1')
                    .show();
            });
        });
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接