If body has this class, then place this content in

2019-06-23 17:04发布

JS beginner here.

I need help with a script to place different content in a div depending on whether the page body tag has a class of "home" or not.

I am trying to use .hasClass & .html to achieve this. It seems like it should be extremely straightforward, but I can't figure it out. Lack of proper syntax knowledge? Incorrect declarations? I don't know, and am hoping someone can point me in the right direction!

    if ($("body").hasClass("home") == true) {
            ("#mobilemenu").html("<a href="#">HOME</a>");
    }
    else {
            ("#mobilemenu").html("<a href="#">NOT HOME</a>");
    }

the JSFiddle (which currently does nothing) is here: http://jsfiddle.net/aqyN4/

Links to other JSFiddles or questions with similar functions extremely welcome!

Thank you,

Ali

标签: jquery class
2条回答
Anthone
2楼-- · 2019-06-23 17:30

you forgot $ before ("#mobilemenu") :

if ($("body").hasClass("home")) {
    $("#mobilemenu").html("<a href='#'>Alle Kategorien- HOME</a>");
}
else {
    $("#mobilemenu").html("<a href='#'>NOT HOME</a>");
}​

demo : http://jsfiddle.net/aqyN4/4/

查看更多
我命由我不由天
3楼-- · 2019-06-23 17:33

hasClass already tests for a true value, you don't need to make a comparison.

Also, the ("#mobilemenu") tags did not have jQuery's $ appended. This makes it an undeclared function. Also...you cannot open a statement with " and use it to encase strings unless you escape it, or use apostrophes. See working code below.

if ($("body").hasClass("home")) {
  $("#mobilemenu").html("<a href='#'>HOME</a>");
}
else{
  $("#mobilemenu").html("<a href='#'>NOT HOME</a>");
}
查看更多
登录 后发表回答