在下面的代码中,我试图获取按钮href属性值,并使用jquery将其显示在警报框中。
当我因为href值(即$value['3'])而点击按钮时,它会重定向到我们的零售商链接,但通过使用jquery,当我使用href属性获得没有页面刷新的按钮链接时,它只会获得任何按钮链接上的第一个链接。事实上,我不想在没有页面刷新的情况下使用特定的按钮链接。
<html><head>
<script src="jquery-1.11.3.js"></script></head>
<script>
$(document).ready(function(){
$('.button').click(function(){
var href = $('a').attr('href');
alert(href);
})
});
</script><body>
<?php
$data=array(
array("HTC desire 210 black","Flipkart",20000,"http://www.flipkart.com"),
array("HTC desire 326 white","Snapdeal",22000,"http://www.snapdeal.com"),
array("HTC desire 516","Amazon",23000,"http://www.amazon.in")
);
foreach($data as $value)
{
?>
<a href="<?php echo $value['3']; ?>"><input type="button" value="Get link's href value" class="button" /></a><br/><br/>
<?php
}
?></body></html>
尝试:
$('.button').click(function(){
var href = $(this).parent('a').attr('href');
alert(href);
})
脚本的更改
<script>
$(document).ready(function(){
$(document).on('click','.button',function(){
var href = $(this).attr('data-link');
alert(href);
})
});
</script>
html 中的更改
<input type="button" value="Get link's href value" class="button" data-link="<?php echo $value['3']; ?>"/><br/><br/>
试试这个,这对我来说很好。
$(document).ready(function(){
$('.button').click(function(){
var href = $(this).closest('a').attr('href');
alert(href);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<a href="http://www.google.com"><button class="button">Google</button></a>
<a href="http://www.yahoo.com"><button class="button">Yahoo</button></a>
<a href="http://www.msn.com"><button class="button">Bing</button></a>
所以你想在点击链接时提醒它的href值吗?使用preventDefault();
$(document).ready(function(){
$('a').click(function(e){
alert( $(this).attr('href') );
e.preventDefault();
return false;
})
});
或者,如果你只想点击一个按钮,那么
$(document).ready(function(){
$('.button').click(function(e){
alert( $(this).parent('a').attr('href') );
e.preventDefault();
return false;
})
});