<div class="header1">
sth
<span>
::before
sth2
</span>
</div>
<div class="pure-menu-link">
sth2
</div>
<script type="text/javascript">
var titleToHide = $('.header1 span').html();
titleToHide = titleToHide.replace('::before', '');
titleToHide.trim();
var titleToCompare = $('.pure-menu-link').html();
titleToCompare.trim();
if (titleToHide === titleToCompare){
$('.pure-menu-link').hide();
};
</script>
我正在尝试比较 header1 和 pure-menu-link 内的 span 内容,当 header1 为空时,我需要隐藏 p-m-l 元素。为什么不起作用?
最佳答案
该问题是由于两个 html()
值之间的空格差异造成的。 trim()
是在比较之前消除任何无关空白的正确方法,但您需要使用其输出更新变量,如下所示:
var titleToCompare = $('.pure-menu-link').html();
var titleToHide = $('.header1 span').html().replace('::before', '');
// note the whitespace difference in the console...
console.log(titleToHide);
console.log(titleToCompare);
// use trim() to fix this
titleToHide = titleToHide.trim();
titleToCompare = titleToCompare.trim();
if (titleToHide === titleToCompare) {
$('.pure-menu-link').hide();
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header1">
sth
<span>
::before
sth2
</span>
</div>
<div class="pure-menu-link">
sth2
</div>
关于javascript - 在jquery中比较div的内容,为什么它不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38310876/