0
var myCode = {};

(function( global ) {
     global.print = function(value){
                   alert("Values: " + value);
                }
            })(myCode);


$(document).ready(function(e) {
    $('[id^=el]').bind("click", function(e) {
        myCode.print("Value");
    });

});

I have this list of anchor elements:

<li>
    <a id="el1"><h3>header 1</h3><p>paragraph 1</p></a>
</li>
<li>
    <a id="el2"><h3>header 2</h3><p>paragraph 2</p></a>
</li>
<li>
    <a id="el3"><h3>header 3</h3><p>paragraph 3</p></a>
</li>
<li>
    <a id="el4"><h3>header 4</h3><p>paragraph 4</p></a>
</li>

How can I bind multiple elements withou writing the binding one If anchor el4 is clicked I want to print Values: header 4, paragraph 4 So how can I get in Jquery the header or paragraph of the respective anchor that is clicked on?

1
  • For one, your HTML isn't valid. You can't nest block-level elements inside of inline elements. Commented Sep 4, 2012 at 14:24

2 Answers 2

1

Looks like this would do it, you need to grab the text value of the h3 & paragraph tags inside of each anchor you're clicking.

$('[id^="el"]').bind("click", function(e) {
    myCode.print($(this).find('h3').text() + ', ' + $(this).find('p').text());
});
Sign up to request clarification or add additional context in comments.

Comments

1

try this

HTML

<li>
    <a id="el1"><h3>header 1</h3><p>paragraph 1</p></a>
</li>
<li>
    <a id="el2"><h3>header 2</h3><p>paragraph 2</p></a>
</li>
<li>
    <a id="el3"><h3>header 3</h3><p>paragraph 3</p></a>
</li>
<li>
    <a id="el4"><h3>header 4</h3><p>paragraph 4</p></a>
</li>

JS CODE

var myCode = {};

(function( global ) {
     global.print = function(value){
                   alert("Values: " + value);
                }
            })(myCode);


$(document).ready(function(e) {
    $('[id^=el]').bind("click", function(e) {
        myCode.print($(this).find('h3').text()+ '  '+ $(this).find('p').text());
    });

});

3 Comments

I want to get them separatelly, like the other answer that does it with find()
sorry i can't see you in time.
Today I finished the votes but tomorrow I will have some again :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.