dongpao1918 2014-07-02 20:11
浏览 36
已采纳

为什么在第三次点击后我的功能不起作用?

I have the following html code:

<?php foreach ($this->tags as $uri=>$tag){?>
    <input type="checkbox" name="tags[]" style="display: none;" value="<?php echo $uri;?>" id="create_<?php echo $uri;?>" <?php echo isset($args['tags']) && in_array($uri, $args['tags'])?'checked="checked"':'';?> />
    <span onclick="selectTag(this.id)" id="create_<?php echo $uri;?>" for="create_<?php echo $uri;?>" class="tag <?php echo isset($args['tags']) && in_array($uri, $args['tags'])?'selected':'';?>"><?php echo str_replace(' ', '&nbsp;', $tag);?></span>
<?php }?>

And here is my JS code:

function selectTag(id) {
    var input = '.tags input#'+id;
    var span = '.tags span#'+id;
    if ($(input).is(':checked') && $(span).hasClass('selected')) {
        $(span).removeClass('selected');
        $(input).attr('checked', false);
    }
    else {
        $(span).addClass('selected');
        $(input).attr('checked', true);
    }
}

When I click on a span box, selects the box, and when I click again on it, it unselects it. The problem is, that after the 3rd time, it just stops working.

What is wrong with my code that is not working?

  • 写回答

2条回答 默认 最新

  • dongqiaozhe5070 2014-07-02 20:18
    关注

    JQuery now has a prop method that is a slightly better alternative to using the attr method.

    Try replacing your calls with attr("checked", true); with calls to prop("checked", true);

    See here for documentation on prop: http://api.jquery.com/prop/

    Here for a discussion between the two: .prop() vs .attr()

    Edit:

    Also, as Ed Cottrell stated, you'll want to have UNIQUE id attributes for all your elements on your page.

    Edit2:

    I have created a fiddle that demonstrates this usage: http://jsfiddle.net/xDaevax/E39hc/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?