简体   繁体   中英

Turning a div into a link

I have a div that I create through javascript. In that div I create a link. This is how I create the div and link:

    $('#info').find('#link').text("View");
    //Creates a new link
    var eventLink1 = document.createElement('a');
    //Sets link attribute
    eventLink1.setAttribute('href', 'Default.aspx?Title=' + responseArray[3].toString() );
    //Adds link to div
    $('#link').empty();
    $('#info').find('#link').append(eventLink1);

When I test the program I find that I can see the link inside the div (through the debugger), but I cannot click on it (It looks as if it is set to display: none but there is no css to back that.

How would I edit the code so that the link is click-able?

You need to do:

eventLink1.appendChild(document.createTextNode('YOUR LINK TEXT HERE'));

The reason why you can't see your link is because there is no text there to see!

Doesn't look like the link has a text component.

<a href="#">Text here is missing</a>

Since you are using jQuery, I suggest you do this sort of thing instead:

var eventLink1 = $('<a></a>')
    .attr('href', 'Default.aspx?Title=' + responseArray[3].toString())
    .text('something here (yours is missing)');
$('#link').empty().append(eventLink1);

The <a> is by default an inline element which completely collapses when it doesn't have a body. So either give it a body, eg some text where you can click on, or set its style to display:block; so that it expands to the parent's size.

As a completely different alternative, you could also just give the <div> an onclick function which sets the window.location to the new URL (along with a style of cursor:pointer; ).

To create the element, you just need this:

$('#link').append('<a href="Default.aspx?Title=' + responseArray[3].toString() +'">Link</a>');

Note: There's no such thing as display: hidden . Also, you do not need to use .find('#link') as the id attribute should be unique on the page. You just need $('#link')

the link doesn't have a text (innerHtml). Here's how you could do it:

$('#link').empty().append($('<a/>',{'href','Default.aspx?Title=' + responseArray[3].toString()}).html('this is the link') );

This is likely because your a tag has no inner text. Try this:

var eventLink1 = $('<a>Your link text</a>').attr('href', 'Default.aspx?Title=' + responseArray[3].toString())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM