问题描述:

I am trying to use jQuery and the .search() function to loop through all of my anchor tags on a page and if it has a certain url, add a data-reveal attribute for a Foundation 5 modal. The code does what it is supposed to but it is throwing an error. This error is keeping scripts below it from being called. Any insight into this matter would be appreciated

When doing this I am getting an error that says : Uncaught TypeError: Cannot read property 'search' of undefined

Here is the script I am using:

<script>

$(document).ready(function(){

$('a').each(function(){

var currLink = $(this).attr('href').search(/oamedia.html/i);

if (currLink != -1) {

$(this).attr('data-reveal-id', 'videoModal')

$(this).attr('href', '#');

};

});

});

</script>

网友答案:

The problem is that attr returns undefined if the attribute is not present. You need an empty string '', rather than undefined. Fortunately, jQuery's prop function does exactly that for the href property:

var currLink = $(this).prop('href').search(/oamedia.html/i);
相关阅读:
Top