1

Below is the HTML and following jQuery. If I return the attr("data-conn"); it alerts the correct value but using .data("conn") it doesn't. Why?

<span>
    <!-- ... -->
    <a href="link.html" class="textbutton"  data-conn="text3">
        <img src="/images/image.png">
    </a>
</span>
<span style="width:610px;height:200px;float:right; background-color:#bcbcbc;font-size:15px;line-height:15px;">
    <div class="texts" id="text1">Initial Header</div>
    <span class="texts" id="text2" style="display:none;">Text for another one</span>
    <span class="texts" id="text3" style="display:none;">Content Text</span>
</span>

<script type="text/javascript">
    $(".textbutton").click(function(){
        var link = $(this).data("conn");
        alert(link);
        $(".texts").fadeOut(1000, function() {
            $("#text2").fadeIn(1000);
        });
        return false;
    });
</script>
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
Somk
  • 11,869
  • 32
  • 97
  • 143
  • 4
    works fine: http://jsfiddle.net/xgwBJ/ – A. Wolff May 27 '13 at 12:16
  • 3
    Which version of jQuery file are you using? – palaѕн May 27 '13 at 12:17
  • what browser are you using ? ( and are you using the html5 doc type? not sure if that has any effect ) – Willem D'Haeseleer May 27 '13 at 12:19
  • 1
    I think I am using an old version of jQuery thanks for pointing that out I hadn't even thought of it – Somk May 27 '13 at 12:22
  • [Seems to work just fine as is to me!](http://jsfiddle.net/SpYk3/urK5L/) using jQuery 1.6.4 – SpYk3HH May 27 '13 at 12:23
  • Although it seems to work fine, I would change one of 2 things. Either change the `return false` to `e.preventDefault()` ***OR*** remove the `return false` and in the HTML change the `href="link.html"` to `href="javascript:void()"`. See my previously mentioned fiddle for `e.preventDefault()` example – SpYk3HH May 27 '13 at 12:26
  • possible duplicate of [jQuery data() returns undefined, attr() returns integer](http://stackoverflow.com/questions/10992984/jquery-data-returns-undefined-attr-returns-integer) – givanse Feb 01 '14 at 19:22

1 Answers1

-1

The way you're trying works fine using the latest version of jQuery:

var link = $(this).data("conn");

Here is a working demo

You may alternatively try like this

var link = $(this).attr("data-conn");
isherwood
  • 58,414
  • 16
  • 114
  • 157
kongaraju
  • 9,344
  • 11
  • 55
  • 78