我创建了 if else 语句来反射(reflect)适当的特定文本,我在这里设置了一个 Jfiddle:http://jsfiddle.net/heykate/osvg4h33/
我想要完成的是,取决于用户是否登录,文本将从登录或创建帐户(如果欢迎访客)或退出(如果已登录,即:欢迎 friend )。
HTML:
<div class="welcome"> Welcome Guest <span class="acctLink"> </span></div>
<div class="welcome"> Welcome Friend <span class="acctLink"> </span></div>
JQUERY:
if ($('.welcome:contains("Guest")').length > 0)
{
$("span.acctLink").html("Sign In Or Create An Account");
}
else
{
$('span.acctLink').html("Sign out");
}
在 JSFiddle 中,它正在验证脚本,但 else 语句周围的括号以绿色突出显示。
跟进
感谢大家的帮助,我能够让 jquery 像预期的那样工作,以及我需要它如何工作。再次感谢您提供的所有帮助,这是我的最终解决方案(可能是一种更好的方法 - 欢迎提供反馈):
HTML:
<div class="welcome">Welcome %%GLOBAL_CurrentCustomerFirstName%% (<span class="customerMenu"> </span>)</div>
JQUERY:
$('.welcome').each(function () {
if ($(this).is(':contains("Guest")')) {
$(this).find("span.customerMenu").html('<a href="/login.php">Sign In<a/> Or <a href="/login.php?action=create_account">Create An Account</a>');
} else {
$(this).find('span.customerMenu').html('<a href="/login.php?action=logout">Sign out</a>');
}
});
最佳答案
我想你正在看这个:
$(".welcome").each(function () {
if ($(this).is(':contains("Guest")')) { //check if element with class welcome contains Guest text
$(this).children("span").html("Sign In Or Create An Account");//find span element and change the text
} else {
$(this).children("span").html("Sign out");//here change span text if div with class welcome doesn't contains Guest text
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="welcome">Welcome Guest <span class="acctLink"> </span>
</div>
<div class="welcome">Welcome Kate <span class="acctLink"> </span>
</div>
引用资料:
关于javascript - 带有 HTML 替换的 Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26391436/