【问题标题】:Jquery: Select full href with a 'contains' methodJquery:使用“包含”方法选择完整的href
【发布时间】:2023-03-21 15:27:02
【问题描述】:

是否可以使用 jQuery 选择一个完整链接,其中 href 包含另一个变量?

我的代码是:

var element1 = $(".not-viewed").parents('li').attr("id");

var element2 = $(".videoTitle").attr("href");

我需要选择一个包含“element1”的完整链接,因为页面中有几个视频。在我的代码中选择页面上的第一个,但我需要带有 id 的特定链接。 示例..[在此示例中,我需要的代码是:1581889025]

    <li class="videoContainer vidLink" id="1581889025">
    <a href="site.com../view/1581889025:49_3eA8F7sPr5FQGZcl2yzx3dz5Y_XwP">
    <span class="HOVER"></span>
    <div class="videoX"><img id="clThumb_1581889025" src="PREVIEW.jpg">
    </div>  </a>
    <a class="videoTitle" href="site.com../view/1581889025:49_3eA8F7sPr5FQGZcl2yzx3dz5Y_XwP">Title of Video</a>
<span class='not-viewed'></span>
<div class="tooltip-footer"></div>
</li>

提前致谢。 亲切的问候。

【问题讨论】:

    标签: jquery select attributes href parents


    【解决方案1】:

    你可以使用attribute-contains selector (*=),像这样:

    var id = $(".not-viewed").parents('li').attr("id");
    var href = $(".videoTitle[href*='" + id + "']").attr("href");
    

    You can give it a try here,您可能还希望 $(".videoTitle[href*='/" + id + ":']") 将其缩小到 /1581889025: 匹配,以防例如 15818890250

    【讨论】:

    • var href = $("a.videoTitle[href*='" + id + "']").attr("href"); - 您应该在选择器中添加“a”,因为其他标记也可能包含 videoTitle 类。 (虽然没多大关系,但我觉得也会快一点。)
    • @Vikash - 这取决于我们更快的浏览器:) 但是是的,这也是一个有效的选择器,我的意思是更多地展示属性部分,而只是澄清,而不是改变其余部分: )
    • 感谢大家,一切工作完美 :-) 我在我的项目中添加了你所有的名字 ;-) 非常感谢..
    • @Luca - 欢迎 :) 如果他们解决了您的问题,请务必接受答案!
    猜你喜欢
    • 2014-07-22
    • 2012-12-01
    • 2019-08-25
    • 2013-03-10
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    相关资源
    最近更新 更多