Javascript 将变量值与元素值进行比较
您好,我想比较一个变量值和一个元素值,如果它们匹配,就应用这个样式 假设我有这个:Javascript 将变量值与元素值进行比较,javascript,jquery,html,css,Javascript,Jquery,Html,Css,您好,我想比较一个变量值和一个元素值,如果它们匹配,就应用这个样式 假设我有这个: // Removed$('#section7').click(function() { $("a[href$='section7']").click(function() { //alert("Test"); $('publishing').clone().appendTo('#publishing-version'); $('#publishing
// Removed$('#section7').click(function() {
$("a[href$='section7']").click(function() {
//alert("Test");
$('publishing').clone().appendTo('#publishing-version');
$('#publishing-version publishing').contents().unwrap();
var pubVer = $('#publishing-version').text();
$("edition-holder a:contains('" + pubVer + "')").css('background-color', 'pink');
console.log(pubVer);
}); //end click func for publishing
我想将下面HTML代码中“edition holder”中的href值与变量pubVer进行比较,如果它们匹配,则将边框样式应用于相应的a href链接
之后我更新了代码,但我尝试了下面发布的代码示例,但仍然未能成功。甚至尝试将下面的代码单独移动到一个新文件中,但都没有成功
我尝试使用包含选择器,但无法显示样式。jQuery中是否有方法匹配字符串?如果字符串相等,则执行此操作
因此,如果用户单击id部分7,则运行此脚本
我在Barmar的回复中看到下面的代码在工作,但在我这一方未能使其工作
页面中较高位置的HTML代码
`**<div id="publishing-version"></div>**` //Places ver from below into this element
<publishing>Vol. 20 | May 2017</publishing>//Changes depending on article issue
<section class="animated slideInRight" style="" id="section7">
<div class="section-heading">
<section-subhead>Want to read previous editions?</section-subhead>
</div>
<div class="row-container">
<edition-container>
<edition-sub>Please choose the desired one</edition-sub>
<edition-holder><a href="/c-conv-content/may/index.html?requestid=cunastuWugufr3dr" class="edition-link">Vol. 20 | May 2017</a>
<a href="/c-conv-content/apr/index.html?requestid=sP2kufuvabu4E4Ey" class="edition-link">Vol. 19 | April 2017</a>
<a href="/c-conv-content/mar/index.html?requestid=s1oex54phlenlaXl" class="edition-link">Vol. 18 | March 2017</a>
<a href="/c-conv-content/feb/index.html?requestId=Niewlazl8yieProU" class="edition-link">Vol. 17 | February 2017</a>
<a href="/c-conv-content/index.html?requestid=dcURzXhdavLss597" class="edition-link">Vol. 16 | January 2017</a>
</edition-holder>
</edition-container>
</div>
<home class="home"><a href="#main-section"><img src="images/home.png">Back to Home Section</a></home>
</section>
`****`//将下面的版本放入此元素中
第20卷| 2017年5月//根据文章发行情况的变化
想看以前的版本吗?
请选择你想要的
您可以使用:contains
。必须将变量与选择器的其余部分连接起来
您想要的版本不在$(“#发布版本”)
中,而是在$(“发布”)
中
var pubVer=$('publishing').text().trim();
$(“版本持有者a:包含(“+pubVer+”))).css('background-color','pink')代码>
出版版本:
第20卷2017年5月
请选择你想要的
感谢您的回复Barmar,但即使将您的代码复制到text.html文件中,我也无法使其正常工作。但困惑的是,当我“运行代码片段”时,它为什么会工作?是否有可能您的#发布版本DIV中的文本周围有额外的空格?请尝试使用.html().trim()
删除它。另外,请使用.text()
而不是.html()
以防有任何不应匹配的嵌入标记。您好,Barmar,我的div标记中删除了空格,因此两个标记位于同一行,没有空格。仍然没有幸运地更新上面的代码和您的建议感谢您的帮助Barmar,我无法使其正常工作请参阅上面的更新代码