jQuery在子元素中查找并替换锚点

时间:2014-05-09 14:34:54

标签: javascript jquery html

我有一些遵循这种模式的HTML:

<p class="title" data-section-title="" style="left: 0px;">
    <a href="#">Overview</a>
</p>

我需要将哈希值更改为锚点,例如<a href="#tab1">Overview</a>

我似乎无法使用jQuery选择它,主要是因为我很糟糕。我正在尝试$("p.title > a").attr("href","http://www.someURL.com");之类的东西只是试图改变href。

任何帮助非常感谢!感谢

5 个答案:

答案 0 :(得分:2)

你的代码完全没问题。我闻到了一些可疑的东西。

我认为你甚至在那里或者没有加载jquery之前就试图访问元素。否则,这个简单的代码应该有效。

试试这个:

  • 检查是否加载了jquery
  • 将您的代码包装在DOM中:

包装是这样的:

$(document).ready(function(){
   //code goes here
});

答案 1 :(得分:2)

正如您所看到的,这适用于jsFiddle:http://jsfiddle.net/GY5D7/。 也许在初始化脚本时出现了问题。试试这个:

$(document).ready(function() {
    $("p.title > a").attr("href","http://www.someURL.com");
});

答案 2 :(得分:2)

尝试使用此代码

$('p.title').find('a').attr('href',"http://www.someURL.com");

抱歉,我错了:(

此致

答案 3 :(得分:2)

试试这个小提琴。 JSFiddle 你的代码似乎没问题。

$(document).ready(function() {
    $("#btn1").click(function(){
        $("p.title > a").attr("href","#tab1");
        alert($("p.title > a").attr("href"));
    });
});

答案 4 :(得分:1)

当Javascript被解雇时,您的HTML是否已呈现?它可能不是。

最简单的解决方法:换入$(document).ready()

有两种方法。普通写法:

$(document).ready(function () {
    $("p.title > a").attr("href","http://www.someURL.com");
});

简写:

$(function() {
    $("p.title > a").attr("href","http://www.someURL.com");
});

其他方式

将其包裹在$(document).ready()中。如果您将该脚本放在正文的末尾,那么它可以工作:

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
    <p class="title" data-section-title="" style="left: 0px;">
        <a href="#">Overview</a>
    </p>
    <script>
        $("p.title > a").attr("href","http://www.someURL.com");
    </script>
</body>
</html>

您可能没有加载jQuery

点击 F12 检查您的控制台。如果您看到如下错误:

<强>铬:

jQuery not loaded in Chrome

<强>火狐:

jQuery not loaded in Firefox

Internet Explorer:

jQuery not loaded in Internet Explorer

然后你需要在你的文档中包含jQuery