动态<a href=""> event without replacing

时间:2016-07-30 14:27:07

标签: javascript php jquery html

Hey im having a problem creating a dynamic ahref event. The problem is that i dont want it to perform the default event of just linking. So i have blocked the default and want to replace content inside a div like so, here is the working code:

echo '<a href="/mydirectory/index.php?id=',$id,'">';
echo '<script>
$( "a" ).click(function( event ) {
  event.preventDefault();
 $(".container2").load("/mydirectory/index.php?id=',$id,'");';
echo '}); </script>';

This works perfectly as i expeted, the problem is that by using this:

$( "a" ).click(function( event ) {

It sets all elements of 'a' on the page to link to the last link clicked. However using a unique ID on the href seems to redirect just directly to the html rather than replacing the content and there are no errors when i checked on chrome:

<a href="/mydirectory/index.php?id=',$id,'" id="mylink">
$( "#mylink" ).click(function( event ) {

So my question is simply, how do i retain the functionality that seems to work for some reason only on the a href and stop it replacing all the a-hrefs elsewhere in the site with the same function?

2 个答案:

答案 0 :(得分:1)

如果您使用必须使用的唯一ID,请注意&#39;#&#39;而不是&#39;。&#39;用于一个类,所以你的代码应该这样

<a href="/mydirectory/index.php?id=',$id,'" id="mylink">
$( "#mylink" ).click(function( event ) {

答案 1 :(得分:1)

我不知道有多少链接和你如何生成,你可以使用&#39;点击&#39;函数和获取attr href比使用它你喜欢的方式。如果您有任何问题请告诉我,请使用event.stopImmediatePropagation()查看代码

<a href="/mydirectory/index.php?id=',$id,'" id="mylink">click me</a>

$('a#mylink').click(function(event) {
    event.preventDefault();
    var link_url = $(this).attr('href');

    alert(link_url);

    event.stopImmediatePropagation();
});