How can I use the href link in the data attribute or rewrite it with jQuery?

I use the data attribute to show credit for a photo on a site:

<div id="test" data-credit="name">

But how can I use the link, for example:

<div id="test" data-credit="<a href="http://mydomain.com">name</a>">

Exiting html like this does not work:

&lt;a href=&quot;http://mydomain.com&quot; &gt;name&lt;/a&gt;

This cannot be done, how can I use jQuery to overwrite the credit data " name" into " <a href="http://mydomain.com">name</a>" on the finished document?

JSfiddle here: http://jsfiddle.net/8muBm/58/

+3
source share
4 answers

An attribute datais simply the owner of the string information. Perhaps you can add another attribute, for exampledata-credlink="http://mydomain.com"

$(document).ready(function () {
    $('div[data-credit]').each(function () {
        var THIS = $(this),
            link = $('<a>', {'href': THIS.attr('data-credlink'),
                              'text': THIS.attr('data-credit')
                            });
        THIS.append(link);
    });
})

<div id="test" data-credit="name" data-credlink="http://mydomain.com"></div>
+2
source

href. data-credit, href . href.

Try:

<div id="test" data-credit="<a href='http://mydomain.com'>name</a>">

HTML , data-credit, :

$('#test').attr('data-credit');
+1

jQuery:

$("div[data-credit]").each(function(){
    $(this).attr("data-credit",'<a href="http://mydomain.com">'+ $(this).attr("data-credit")+'</a>');
});

div data-credit, URL- . , HTML-?

: http://jsfiddle.net/niklasvh/fBW4V/

0

Basically, you use double quotes inside double quotes, this leads to invalidation of the attribute. You need to either change the encapsulating quotes to single quotes, or change the quotes inside the attribute value to single quotes.

Here is what I mean:

<div id="test" data-credit="<a href='http://example.com'>name</a>">

Here is a simple example that you can use for testing:

<head>
<!-- Assume jQuery is loaded -->
<script type="text/javascript">
$(document).ready(function() {
    $("#v").val($("#test").attr("data-credit"));
});
</script>

</head>
<body>

<div id="test" 
    data-credit="<a href='http://example.com'>name</a>">
<input id="v" type="text" value="" />

</body>
</html>

Please note that using escaped html works .

0
source

All Articles