Deep-linking via <div> block and attribute title='', and toggleClass 'selected'

StackOverflow https://stackoverflow.com/questions/14996395

  •  10-03-2022
  •  | 
  •  

質問

Refer to jsfiddle demo that I have created here, I'm trying to add in deep-linking features for my current client's website.

I need help with the following requirements:

My simple click toggleClass code:

$("div.contentBox").click(function () {

    var $this = $(this);
    // don't proceed if already selected
    var $previousSelected = $('.selected');
    if ( !$this.hasClass('selected') ) {
        $this.addClass('selected');
    }

    $previousSelected.removeClass('selected');  
});



(1) There will be many repetitive <div class='contentBox'> with each having different value for its attribute title=''

(2) Event trigger via $("div.contentBox").click() adding value from title='', will churned out something like http://site.com/index.html#content01-about-us. Note: please provide sample coding how to achieve this.

(3) The reason of triggering event via <div> block instead of <a> is due to additional <a> tags inside of container class='contentBox', and will eventually form nested <a> links, which is not allowed.

(4) $("div.contentBox").click() will also toggleClass 'selected'

(5) Returning from links, example http://site.com/index.html#content01-about-us, page load will be smart enough to get <div class='contentBox' title='content01-about-us> to addClass/toggle class 'selected'

I had spent weeks figuring this out, but to no avail, desperately need help here. It would be best if anyone here kind enough to update the above jsfiddle demo as per requirement stated.

Been through some research myself and came across history.js, address.js and BBQ plugin, but just couldn't get it to work



Many thanks in advance

役に立ちましたか?

解決

Do you need something like this:

$("div.contentBox").click(function () {

var $this = $(this);
// don't proceed if already selected
var $previousSelected = $('.selected');
if ( !$this.hasClass('selected') ) {
    $this.addClass('selected');
}
$previousSelected.removeClass('selected');  

if(location.href.indexOf('#') == -1)
  location.href += "#" + $(this).prop("title");
else
  location.href = location.href.split('#')[0] + "#" + $(this).prop("title");
alert(location.href);
});

And for second requirement:

$(document).ready(function() {
  if(location.href.indexOf('#') != -1){
    var page = location.href.split('#')[1];
    $("div[title*=" + page + "]").addClass('selected');
  }
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top