How can I use an href link within a "data" attribute - or rewrite it with jQuery?
I'm using the data attribute to show a credit for a photo on a site:
<div id="test" data-credit="name">
But how do I do use a link, like this?:
<div id="test" data-credit="<a href="http://mydomain.com">name</a>">
Escaping the html, like this, doesn't work:
<a href="http://mydomain.com" >name</a>
It that can't be done, how would I use jQuery to rewrite t开发者_StackOverflow社区he data-credit "name
" into "<a href="http://mydomain.com">name</a>
" on document ready?
JSfiddle here: http://jsfiddle.net/8muBm/58/
The data
attribute is just a holder for string information. You could probably add another attribute like data-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>
The issue is in the double quotes around the href value. Since you are using double quotes for The data-credit attribute, you would need to change the quotes around the href attribute to single quotes. Otherwise, you are closing the data-credit double quotes with the opening href double quote.
Try:
<div id="test" data-credit="<a href='http://mydomain.com'>name</a>">
If the HTML markup is in-tact, you could then easily access the data-credit attribute, for example:
$('#test').attr('data-credit');
This should perform the rewrite with jQuery:
$("div[data-credit]").each(function(){
$(this).attr("data-credit",'<a href="http://mydomain.com">'+ $(this).attr("data-credit")+'</a>');
});
It looks for all div elements with data-credit attribute, gets that attribute and wraps it around that url and assigns it back to the attribute. But as Felix already asked, why would you want to store the full HTML there?
Example: http://jsfiddle.net/niklasvh/fBW4V/
Basically, you are using double quotes inside of double quotes, this invalidates the attribute. You either have to change the encapsulating quotes to single quotes, or change the quotes inside the attribute value to single quotes.
Here's what I mean:
<div id="test" data-credit="<a href='http://example.com'>name</a>">
Here's a simple example you can use to test:
<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>
Note that using the escaped html does seem to work.
精彩评论