【问题标题】:How to change href value of certain element [duplicate]如何更改某些元素的href值[重复]
【发布时间】:2014-01-12 14:50:40
【问题描述】:

我有类似这样的 HTML 结构

<div id="DeltaPlaceHolderLeftNavBar">
   <div>
   <div>
      <ul>
         <li><a href="link1.php"><span class="someclass">LINK1</span></a>
            <ul>
               <li><a href="link1a.php"><span class="someclass">LINK1A</span></a></li>
            </ul>
         </li>
         <li><a href="link2.php"><span class="someclass">LINK2</span></a></li>
      </ul>
   </div>
   </div>
</div>

我想更改那些包含子 UL 的 LI 的 HREF。如您所见,LINK1 内部包含 UL,但 LINK2 没有,因此我编写了以下 jquery 代码,但它不起作用。

$('#DeltaPlaceHolderLeftNavBar div>div>ul>li>a').click(function()
{
   if($(this).closest("li").children("ul").length > 0)
   {
      //the code comes inside this condition but following line doesn't work
      $(this).closest("li").children("ul").attr("href","#");
   }
});

编辑

在代码中添加“href”标签

编辑 在 HTML 中犯了一个错误,因为我忘记了我现在添加的一个 div。

【问题讨论】:

标签: jquery css


【解决方案1】:

我认为你只需要更改代码

$(this).closest("li").children("ul").attr("href","#");

$(this).closest("li").children("a").attr("href","#");

在你的 if 条件下。
现在你的点击事件函数变成了:

$('#DeltaPlaceHolderLeftNavBar div>div>ul>li>a').click(function(event)
{
    event.preventDefault();

    if($(this).closest("li").children("ul").length > 0)
    {
        //the code comes inside this condition but following line doesn't work
        $(this).closest("li").children("a").attr("href","#");
    }  
});  

这里我添加了event 作为函数参数和event.preventDefault() 以防止默认您的链接点击事件不会重定向到链接地址。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 2017-12-01
    • 2020-05-30
    • 2012-06-21
    • 1970-01-01
    相关资源
    最近更新 更多