简体   繁体   中英

Jquery to get the contents of a div

How can I get the contents of a <div> when a link is clicked

eg :

there are two div tags

<div id="1" > This Is First Div </div>
<div id="2" > This Is Second Div </div>
<a href="#" id="click" >Click Here</a>

When the link is clicked, I need to get the content as:

This Is Fist Div
This Is Second Div

If I well understood

$('a').on('click', function(ev) {
   ev.preventDefault();
   $($(this).prevAll('div').get().reverse()).each(function() {
     alert ($(this).text())
   })
});

As a sidenote, the id attributes you choose are not valid (they cannot start with a digit)

Example fiddle : http://jsfiddle.net/533qX/

edit. With one single alert

$('a').on('click', function(ev) {
   var text = "";
   ev.preventDefault();
   $($(this).prevAll('div').get().reverse()).each(function() {
     text += $(this).text() + "\n";
   })
   alert(text);
});
function alertDiv(divId){
    $('#click').on('click', function(e){
       alert ($(divId).text());
       e.preventDefault();
    });
}

alertDiv('#one');
alertDiv('#two');

http://jsbin.com/ebowim/2/edit

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