Я пытался создать пользовательское решение с использованием jQuery , которое имитировало бы то же поведение, что и тег a
, для родительского DIV.
DEMO: https://jsfiddle.net/kutec/m9vxhcke/
Согласно стандарту W3C, вы не можете сделать это:
<div class="boxes">
<a href="http://link1.com" target="_blank">
<div class="box">
<h3>Link with _blank attr</h3>
</div>
</a>
</div>
Вы должны следовать этому:
<div class="boxes">
<div class="box">
<h3>
<a href="http://link1.com" target="_blank">Link with _blank attr</a>
</h3>
</div>
</div>
Но, следуя приведенному выше коду, вы не сможетет получить весь DIV, интерактивный:).
Правильная структура должна быть примерно такой, что также позволяет вам щелкнуть по DIV, чтобы перенаправить на указанное значение href
:
<div class="boxes" data-href="http://link1.com" data-target="_blank">
<div class="box">
<h3>
<a href="http://link1.com" target="_blank">Link with _blank attr</a>
</h3>
</div>
</div>
Простое решение :
$(function() {
$('.boxes a').each(function(){
var aTag = $(this).attr('href');
$(this).parent().attr('data-href',aTag);
$("[data-href]").click(function() {
window.location.href = $(this).attr("data-href");
return false;
});
})
}(jQuery));
Динамическое решение :
(function ( $ ) {
$.fn.dataURL = function() {
// variables
var el = $(this);
var aTag = el.find('a');
var aHref;
var aTarget;
// get & set attributes
aTag.each(function() {
var aHref = $(this).attr('href');
$(this).parent().attr('data-href',this);
aTarget = $(this).attr('target');
$(this).parent().attr('data-target',aTarget);
});
// imitation - default attributes' behavior on "data-" attributes
$(el).delegate('[data-href]','click', function() {
var loc = window.location.href;
loc = $(this).attr("data-href");
aTarget = $(this).attr('data-target');
if(aTarget == "_blank"){
window.open(loc);
} else {
window.location = loc;
}
return false;
});
//removing attributes from selector itself
el.removeAttr('data-href');
el.removeAttr('data-target');
// css
$('[data-href]').css('cursor','pointer');
};
}( jQuery ));
Окончательный вызов :
<script>
$('.boxes').dataURL();
</script>
Надеюсь, это будет полезно:)