html - jquery .data() is not attaching data to element -
i when user clicks on "2" button (code below) data attribute of clicked = true
should appear on button. when user clicks on "3" button "2" button clicked
data should removed , 3 button data attribute should clicked = true
. right looks cant simple thing placing data on element , interact it
html:
<body> <button class = "two">2</button> <button class="three">3</button> </body>
script:
$(document).ready( function(){ //when user clicks on button button should show signs of data attr $('.two').on('click',function(e){ $(this).data('clicked', true); //alert('sup') }) if($('.two').data('clicked')){ alert('received data') } });
i tried following this chosen answer toggle data attr figure out element clicked perform operations later in code
i think trying store clicked button retrieve later.
in such case better use class based solution like
$(document).ready(function() { //when user clicks on button button should show signs of data attr var $clicks = $('.clicks').on('click', function(e) { $(this).addclass('clicked'); $clicks.not(this).removeclass('clicked'); }); $('#test').click(function() { alert($('.clicks.clicked').text()) }) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button class="two clicks">2</button> <button class="three clicks">3</button> <br /> <button id="test">test</button>
if want continue sing data-clicked
attribute, need use .attr()
not .data()
.data()
not update attribute value
$(document).ready(function() { //when user clicks on button button should show signs of data attr var $clicks = $('.clicks').on('click', function(e) { $(this).attr('data-clicked', 'true'); $clicks.not(this).removeattr('data-clicked'); }); $('#test').click(function() { alert($('.clicks[data-clicked]').text()) }) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button class="two clicks">2</button> <button class="three clicks">3</button> <br /> <button id="test">test</button>
Comments
Post a Comment