问题描述:

I am having an issue with accessing an attribute of an anchor with PrototypeJS 1.6.0.3.

My code below works when I hard-code the course_number variable, however I would like to be able to extract it from the anchor.

This is my anchor tag:

<a class="course_number_info_link" data-course-number="{$foo}" href="#">{$foo}</a>

This is my invoke method observing a click on the anchor:

$$('.course_number_info_link').invoke('observe', 'click', this.getCourseInfo(this));

This is my getCourseInfo method, however the course_number doesn't pull through. How can I get access to the data attribute?

 getCourseInfo: function(element) {

var course_number = element.readAttribute('data-course-number');

console.log(course_number);

new Ajax.Updater('result-' + course_number, '/ajax/get_course_info.php', {

parameters: { course_no: course_number },

onSuccess: function(response) {

console.log(response);

}

});

}

网友答案:

the way you are setting up the observer is why it is failing - you are passing a complete function to the observer instead of the function reference

If this is ran inside of your object then this is the object instead of the element

$$('.course_number_info_link').invoke('observe', 'click', this.getCourseInfo(this));

should be

$$('.course_number_info_link').invoke('observe', 'click', this.getCourseInfo);

the parameter that is passed into getCourseInfo() will be an Event object not an element object - this should be the element object or you can also get the element like this

getCourseInfo: function(event) {

   var element = event.findElement();
   var course_number = element.readAttribute('data-course-number');
//snip....
网友答案:

While the answer provided by Geek Num 88 is correct in pointing out the wrong setup of the observer, it doesn't fully explain how to correctly access the data-* attributes. Of course the easiest way would be prototype's Element.readAttribute() but you can also use the native Element.dataset which is available on all modern browsers. So instead of:

var course_number = element.readAttribute('data-course-number');

you could just use:

var course_number = element.dataset.courseNumber;

If you need a fallback for older browsers, you could implement something like this:

Element.addMethods({
    addDataset: function(e){
        if(!(e = $(e))){
            return;
        }
        if(!e.dataset){
            e.dataset = {};
            $A(e.attributes).each(function(a){
                if(a.name.match(/^data-/)){
                    e.dataset[a.name.substr(5).camelize()] = a.value;
                }
            });
        }
        return e;
    }
});
相关阅读:
Top