简体   繁体   中英

Pass parameter from a div to a javascript function

The script below has a parameter called loadurl . The loadurl represents a page that is retrieved with an ajax call to the database. I want to dynamically supply a url to the $.get() function with an onclick command in a div

$(".get").click(function ()
     {
         $.get(loadUrl, 
              function (responseText){
              $("#result").html(responseText);
             });
     }
   );

Html code that i want to supply the new url to $.get() function

<div onclick="$.get()" class="get"> page 1</div>  
<div onclick="$.get()" class="get"> page 2</div> 

Thanks

why don't you use an a tag and use the href attribute?

$(".get").click(function ()
     {
         $.get($(this).attr('href'), 
              function (responseText){
              $("#result").html(responseText);
             });
         return false;
     }
   );

Here would be some html.

<a href="url" class="get"> page 1</a>  
<a href="url2" class="get"> page 2</a> 

I changed you jquery-ness to use more built in javascript to make it easier to read and understand

HTML:

<div onclick="javascript:get(this)" class="get"> page 1</div>  
<div onclick="javascript:get(this)" class="get"> page 2</div> 

And the javascript:

 function get(div)
         {
             $.get(div.innerHTML, 
                  function (responseText){
                  $("#result").html(responseText);
                 });
         }
       );

By the looks of what you're asking, you want the content of the div (the text in the div) to be used as the URL for the ajax request.

You can get the text by doing:

$(this).text()

So that:

$(".get").click(function ()
     {
         $.get($(this).text(), 
              function (responseText){
              $("#result").html(responseText);
             });
     }
   )

it looks a little over specified. You could try something like:

$(".get").click(function () {
     $.get($(this).attr("loadUrl") , 
          function (responseText){
          $("#result").html(responseText);
         });
   }
);

<a loadUrl="url" class="get"> page 1</a>  
<a loadUrl="url2" class="get"> page 2</a> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM