obtener el nombre del encabezado como url usando jquery

<div class="myclass selected">
    <h2 class = "title">#Content 1</h2>
</div>
<div class="myclass">
    <h2 class = "title">#Content 2</h2>
</div>
<div class="myclass">
    <h2 class = "title">#Content 3</h2>
</div>
<div class="myclass">
    <h2 class = "title">#Content 4</h2>
</div>

I want to show as "http://example.com/#content-1" in url and want to update for each selection. Is this possible to do that using jquery ?

preguntado el 24 de agosto de 12 a las 02:08

do you want to click at #Content 1 and change url? -

Your question is unclear, please provide more information. -

I have no idea what you want. -

i want to change the url when i click using the next click funtion. -

I believe that you want anchors instead of h2 -

2 Respuestas

$('.myclass h2').click(function(){
    window.location = 'http://example.com/' + $.text(this).toLowerCase().replace(/ /g, '-');
});

Is there any reason you're not using regular links? Try this:

<div class="myclass selected">
    <h2 class="title">
        <a href="#content-1">#Content 1</a>
    </h2>
</div>
<!-- Add the others here... -->

Then, just add this script:

jQuery(function() {
    var hash = window.location.hash;
    hash && $('.myclass').removeClass('selected').filter(function(){
        return $(this).find('a').prop('href') == hash;
    }).addClass('selected');
});

Respondido 24 ago 12, 02:08

También podemos usar window.location.hash. - Carnero

@undefined - The OP has not specified that they're currently on http://example.com/. - José Silber

In this code, when i refresh the page it starts from initial. Is this possible to get the same content which is on the url even i refresh the page ? - user1621335

@user1621335 - I'm verdaderamente sorry, but I do not understand your question. - José Silber

if this is my link "example.com/#content-3". when i refresh my page, it doesn't show the content 3. instead of that it show the content 1. Sorry for my bad english. - user1621335

Cambia esto

 var selected = $('.selected');
    selected.removeClass('selected');
    selected.hide();

    var next = selected.next(".myclass");

a

 var selected = $('.selected');
 var next = selected.next(".myclass");
 selected.removeClass('selected');
 selected.hide();

You are removing the class selected antes de asignarlo a next..

http://jsfiddle.net/wirey00/Jqfsn/1/

Respondido 24 ago 12, 05:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.