javascript - 用 Jquery 替换 URL 值

标签 javascript jquery html

我有以下 HTML

<div class='tile'>
    <a href='http://test-site.local' >
        <div class='tileContents'>
            <div class='tileImage'>
                <i class='icon-'></i>
            </div>
            <div class='tileCaption'>
                <h4>Logos</h4>
                <p></p>
            </div>
        </div>
    </a>
</div>

<div class='tile'>
    <a href='http://test-site.local' >
        <div class='tileContents'>
            <div class='tileImage'>
                <i class='icon-'></i>
            </div>
            <div class='tileCaption'>
                <h4>Adverts</h4>
                <p></p>
            </div>
        </div>
    </a>
</div>

我想将 href 属性更新为我希望使用 h4 标记的值作为目标和区分两个 DIV 的任何 URL相同的类名。

例如,我想将第一个 div 的 a 标记中的 URL 更新为:

<a  href="http://www.google.com">

so if the value of the h4 tag = "Logos" then update the URL to "http://www.google.com"

第二个 DIV 也是如此:

<a href="http://www.yahoo.com">

so if the value of the h4 tag = "Adverts" then update the URL to "http://www.yahoo.com"

我有以下内容,但我认为我没有正确获取选择器:

<script src="/script/jquery-1.10.2.min.js" type="text/javascript"></script>  
<script type="text/javascript">
$(document).ready(function(){  
    var value = $('div.tile h4').html();
    if (value = "Logos");
    $("DIV.tile a").attr("href", "http://www.google.com");
    if (value = "Adverts");
    $("DIV.tile a").attr("href", "http://www.yahoo.com");
});
</script>

如有任何帮助,我们将不胜感激..

最佳答案

遍历每个图 block 并更改其 children('a') 的 href

$('.tile').each(function(){
   $(this).children('a').attr("href", "http://test-site.local/"+$(this).find('h4').text());
});

.find().children() 的区别在于 .find() 在元素内部找到你想要的东西,而.children() 仅沿着 DOM 树向下移动一个级别(因此速度更快)。

使用 .text() 获取单词并将其简单地放在 url 后面而不是使用 if 语句(这样会更快)。

关于javascript - 用 Jquery 替换 URL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19275926/

相关文章:

javascript - 使用字符串插值进行函数调用

jquery - KendoUI Grid - 可以动态更改字体大小以适应列宽吗?

javascript - 查找特定类上方列表项的第一次出现 - JQuery

python - Tex 标记,如何使用 Python 在 Html 中呈现它?

javascript - RxJS 运算符在完成之前不会再次发送到内部可观察对象

javascript - 使用 Node 的 ffmpeg 应用程序偶尔会崩溃,因为文件似乎没有被正确读取

javascript - 更新查询字符串 onChange - ReactJS

带有 HTML 值的 Jquery UI 进度条

html - Handlebars 将 '@partial-block' 内容移动到页面末尾

html - 标题和部分相互合并/重叠