【问题标题】:Concatenation of selector with dynamic value not working - Jquery选择器与动态值的串联不起作用 - Jquery
【发布时间】:2018-06-03 05:46:26
【问题描述】:

我正在尝试删除 a href 背景的样式。问题是当我将动态 id 与选择器连接时它不起作用。但是当我使用选择器的完整名称时,它就可以工作了。 我知道您可以像here 一样将我的问题标记为重复,但它们对我不起作用。请纠正我。

什么有效:

$("a").click(function(event) 
{
     var id = event.target.id;
     $('#chatIdStyle4').removeAttr("style");
});

什么没有:

$("a").click(function(event) 
{
     var id = event.target.id;
     $('#chatIdStyle'+id).removeAttr("style");
});

$("a").click(function(event) {
      //alert(event.target.id);
      var iddds = event.target.id;
      $('#chatIdStyle["'+ iddds + '"]').removeAttr("style");
});

注意:var id 包含触发事件的动态 id。

按要求编辑:

下面是我的 HTML+PHP 代码。所以,它实际上是用动态 id 创建了 4 个动态 a href。我什么 想要的是当一个特定的 a href 被点击时,它应该删除以前的 a href 背景和 为点击的a href添加背景。

<?php
    $color = false;
    $PID = 4;
    for($i=0;$i<4;$i++)
    {
?>
    <a <?php if($color==true)
            {
                ?> style="background-color: #E6E6E6;" <?php
            }
            $color=false;
        ?>
        id="chatIdStyle<?php echo $PID; ?>"
        href="#">
    </a>
<?php
    }
?>

【问题讨论】:

  • id=""中的ID吗?
  • 也许尝试调试你的代码?
  • console.log( event.target.id ) 的输出是什么? 4chatIdStyle4?
  • 如果id 已经包含动态id 那么为什么要连接chatIdStyle?为什么不直接使用$('#' + event.target.id)
  • 您能否发布一个功能示例来说明您的问题。您也可以在编辑模式下点击标题中的&lt;&gt;图标添加演示。

标签: javascript jquery jquery-selectors


【解决方案1】:

我建议使用 CSS 解决方案而不是 jQuery:

a { background: none; }
a:active { background: #E6E6E6; }

第二行将为最后一次点击的a元素设置背景。

关于:active伪类:https://www.w3schools.com/cssref/sel_active.asp

【讨论】:

    猜你喜欢
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多