0

Is it possible to find particular data inside an element on a click, and then write that data to a variable)?

For example, I have a list, with elements of class "datasource" that navigate to "#dataviewer":

<ul>
   <li class="datasource">
      <a href="#dataviewer" >Get this data</a>
   </li>
</ul>

I know I can target that specific list element using something like this:

$(".datasource").click(function() {
        alert("Click!");
});

... but can I fetch the "Get this data" and write it to a variable, in order to use that data on the '#datasource' page?

Many thanks.

4

2 に答える 2

1

"Get this data" is able to be retrieved by the .html() function. Switch out your alert for the following:

alert($("a").html());

You can obviously be as selective as you want to find the "a" element based on the rest of your page.

To store the value into a variable, just store that output like this:

// Probably not exactly what you want when there are many "a"nchor tags on a page.
var contentsOfElement = $("a").html();
// More selective based on an ID
var contentsOfElement = $("#oneParticularID").html();
// Then you can write that text, store it, or whatever you'd like

Using your code as a template, I created this running example.

The documentation for .html().

于 2012-04-20T15:19:04.840 に答える
1

With a listview like this:

<div data-role="page">
<ul data-role="listview">
   <li class="datasource">
      <a href="#dataviewer" >Row A</a>
   </li>
   <li class="datasource">
      <a href="#dataviewer" >Row B</a>
   </li>

</ul>
</div>​​​​​​​

You could use a click handler like this:

​$(".datasource").click (function () {
   alert( $(this).find('a').first().html() );
});​​​​​
于 2012-04-20T15:42:14.413 に答える