1

I have function

    $('body').on('click', '.urlsend', function ()
    {
         console.log("this.parameter");
    }

and all elements with ".urlsend" have some parameter, which I need to pass to the function. HTML looks like this:

<div id="canvas">

</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function loadImgs(){

<!--somecode-->

  function gotData(arr){
    var element="";
    for(var i = 0;i<arr.data.length;i++)
    {
        var img = arr.data[i].images.original.url;
        element += '<img src="'+img+'" class="urlsend" data-url="'+img+'">';

    }
    $('#canvas').html(element);
  }

}
</script>

3 Answers3

2

You can use .attr to get parameter or attribute of an HTML element.

$(document).ready(function() {
  $('body').on('click', '.urlsend', function() {
    console.log($(this).attr("parameter"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="urlsend" parameter="1"> urlsend DIV 1</div>
<div class="urlsend" parameter="2"> urlsend DIV 2</div>
<div class="urlsend" parameter="3"> urlsend DIV 3</div>
<div class="urlsend" parameter="4"> urlsend DIV 4</div>

Doc: http://api.jquery.com/attr/

Eddie
  • 26,593
  • 6
  • 36
  • 58
0

this within the callback will be the specific .urlsend element that the event relates to, so you can access the information from this.

For instance, if the "parameter" is a data-info attribute:

console.log(this.getAttribute("data-info"));

or with more jQuery:

console.log($(this).attr("data-info"));

(Don't use .data(...) unless you want the features it provides, see this answer for details.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

try this

  <script>
     $(function(){
       $('body').on('click' , ' .urlsend' , function(){
    var url=$(this).data('url');
   var user=$(this).data('user');
alert(url);
alert(user);
  });
  });
</script>    

<body>
<button class="urlsend" data-url="google.com" data-user="kate">click</button>
</body>

hope this help you

Seybanks
  • 88
  • 10