robert
robert

Reputation: 8717

Event target changes in jquery randomly

I have a number of hyperlinks in a ul, and I want to capture clicks on the hyperlinks

The structure of div is as below,

<div style="margin:3%;" id="city-list">
        <ul data-role="listview" data-theme="b"  data-filter="true" data-filter-placeholder="Filter Cities...">
            <?php foreach($cities as $city): ?>
            <li>
                <a id="city_<?php echo $city['city_id'] .'_'. $city['city_name']?>" href="#">
                    <span style="font-size: 14px;"><?php echo $city['city_name']; ?></span><br/>
                </a>
            </li>
            <?php endforeach; ?>
            <li class="no-results" style="display:none;">No results found.</li>
        </ul>
    </div>

The jQuery code to capture the click is below,

$("#city-list").delegate('a','click', function(event) {
    event.preventDefault();
     //       console.log(event.target);
    var city_id = event.target.id,
    service_type = "<?php echo $service_type; ?>";
    JE.search_regions(city_id, service_type);
    $.cookies.set('city_id', city_id);
});

This works most of the time, except at some random times.

That time, the event.target is the span inside the a tag. I dont know why this happens.

Please help me to debug this.

Upvotes: 1

Views: 141

Answers (2)

Jaspreet Chahal
Jaspreet Chahal

Reputation: 2750

why don't you use

var city_id = jQuery(this).attr("id");

rather than

var city_id = event.target.id;

Cheers!

Upvotes: 0

adeneo
adeneo

Reputation: 318342

e.target is the actual element clicked, so if you click the span element, e.target will be the span element, but the click bubbles up to parent elements, so the function will still run even if it's attached to a parent element, which is natural as the span is inside the a, and a click on the span is also a click on the a element, but e.target will identify exactly what element actually received the click.

To reference the a element use the this keyword instead, which will reference the bound element, in this case the a element.

Upvotes: 4

Related Questions