0

Do anyone has similar experience? I would like to get the custom parameter when I click on the image rather than only the id. I got undefined for second alert(this.ads), how can I get the number 2 from this parameter?

HTML

<section id="home" data-role="page">
    <article data-role="content">
        <div id="home-content">Home Content here <a href="#tab-3" data-transition="slide">Goto Tab-3</a>
        <div id="tab-3-list">
            <div class="ui-grid-a">
                <div class="ui-block-a">
                    <img id="c02" ads="2" class="coupon_list" src="/images/coupon/c02.png">
                </div>
            </div>
            <!-- /ui-grid-a -->
        </div>
        <!-- /tab-3-list -->
        </div>
    </article>
    <!-- content -->
</section>
<!-- home -->

Javascript

$(document).ready(function () {
    $("#tab-3-list img.coupon_list").on("click", function (e) {
        e.preventDefault();
        alert(this.id);
        alert(this.ads);
    });

});
Kelvin
  • 577
  • 7
  • 25
  • [Is it OK to add your own attributes to HTML elements?](https://stackoverflow.com/questions/1305734/is-it-ok-to-add-your-own-attributes-to-html-elements) – Bergi Jun 15 '14 at 14:12
  • possible duplicate of [Custom attributes - Yea or nay?](http://stackoverflow.com/questions/992115/custom-attributes-yea-or-nay) – Afzaal Ahmad Zeeshan Jun 15 '14 at 14:25

3 Answers3

1

Maybe by using,

alert($(this).attr('ads'));

It would provide you with the custom attribute's value.

EDIT: Adding Custom Attribute for JavaScript's Use

If you want to add a custom attribute just to use it for your own good, like getting more data details in the HTML elements for further usage by the JavaScript.

You can use data- attribute. It would be easy and simple. Here is an example for that

<img data-abs="2" src="/images/coupon/c02.png" alt="coupon photo" />

Now, you can use .data() method to get out the values, http://api.jquery.com/data/ (jQuery API for data method).

Here is how you can use it

$('img').data('abs'); // output would be 2
Community
  • 1
  • 1
Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
0

"ads" is an attribute of the img-tag, so you can get its value with

alert($(this).attr("ads"));

jQuery .attr()

CRoemheld
  • 889
  • 7
  • 26
0

Replace ads with data-ads which is correct according to HTML5.

Then use either native javascript:

this.getAttribute('data-ads');

or jQuery:

$(this).data('ads');
//or
$(this).attr('data-ads');
MarioDS
  • 12,895
  • 15
  • 65
  • 121