jQuery .html()在if语句中不起作用

诺亚·胡珀特(Noah Huppert)

当您发布文章时,我正在为网站创建管理屏幕。我已经做到了,所以一个表包含了帖子的所有值。

<table>
    <tr>
        <th>Post Title</th>
        <th>Post Content</th>
        <th>Tag</th>
    </tr>
    <tr>
        <td id="examplePostTitle">Post Title</td>
        <td id="examplePostContent">First 35 charecters of post........</td>
        <td id="examplePostTag">Post Tag</td>
        <td class="postEditButton" id="examplePostButton">edit</td>
    </tr>
</table>

我已经用jquery编码了一些javascript,以便当用户单击“ edit”时,这些行将由输入框填充。

var click = 1;

if (click == 1) {
    $('#examplePostButton').click(function() {
        $('#examplePostTitle').html('<input type="text" value="Post Title" size="10"/>');
        $('#examplePostContent').html('<input type="text" value="First 35 characters of     post........" size="20"/>');
        $('#examplePostTag').html('<select><option>Animation</option><option>Programing</option>        <option>Robotics</option><option>Other</option></select>');
        click = 2;
    });
}

if (click == 2) {
    $('#examplePostButton').click(function() {
        $('#examplePostTitle').html('Post Title');
        $('#examplePostContent').html('First 35 characters of post........');
        $('#examplePostTag').html('Post Tag');
        click = 1;
    });
}

由于某种原因,您可以单击一次编辑按钮,它将变为输入框。然后,当您再次单击它时,它不会更改变量,也不会还原回非输入框。我已经使用多个js和jquery验证器检查了我的代码,所以我不太确定为什么第二单击功能不起作用。

tl:dr:
我有一些javascript和jquery代码,不起作用,有帮助。
Jsfiddle

丹尼斯·塞古瑞特(DenysSéguret)

您似乎有一个逻辑问题。您必须测试click事件处理程序内部的您可能想要这样:

var click = 1;
$('#examplePostButton').click(function() {
    if (click == 1) {
        $('#examplePostTitle').html('<input type="text" value="Post Title" size="10"/>');
        $('#examplePostContent').html('<input type="text" value="First 35 characters of     post........" size="20"/>');
        $('#examplePostTag').html('<select><option>Animation</option><option>Programing</option>        <option>Robotics</option><option>Other</option></select>');
        click = 2;
    } else if (click == 2) {
        $('#examplePostTitle').html('Post Title');
        $('#examplePostContent').html('First 35 characters of post........');
        $('#examplePostTag').html('Post Tag');
        click = 1;
    }
});

请注意,您可以click通过使用闭包来避免使用全局变量:

(function(){
    var click = 1;
    $('#examplePostButton').click(function() {
         ... rest of the code is identical
    });
)();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章