I'm trying to convert some hard-coded inline onclicks to be dynamically created.
Here's what they look like now:
(html)
<ul id="search-navlist">
<li><a href="#" onclick="searchExhibitorsByAlphabet(this,'A'); return false;">A</a></li>
<li><a href="#" onclick="searchExhibitorsByAlphabet(this,'B'); return false;">B</a></li>
<li><a href="#" onclick="searchExhibitorsByAlphabet(this,'C'); return false;">C</a></li>
....
<li><a href="#" onclick="searchExhibitorsByAlphabet(this,'Z'); return false;">Z</a></li>
</ul>
Here's the new code:
(script)
$(document).ready(function() {
$('#search-navlist li a').each(function() {
$(this).attr("onclick", "searchExhibitorsByAlphabet(this,'A'); return false;");
});
});
(in html)
<ul id="search-navlist">
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li><a href="#">C</a></li>
....
<li><a href="#">Z</a></li>
</ul>
So far, this works fine, although all of the links are the same. I'd like the links to be associated with it's respective letter.
I found this function:
function iterateAlphabet() {
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(var i=0; i<str.length; i++) {
var nextChar = str.charAt(i);
alert(nextChar)
}
}
...but am uncertain as to how to incorporate it. (I also saw some script using charcodes, the above function was easier for me to understand.)
I'开发者_如何转开发d appreciate some help. I'll continue trying in the meantime.
Thanks.
You can rewrite as:
<ul id="search-navlist">
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li><a href="#">C</a></li>
....
<li><a href="#">Z</a></li>
</ul>
$(document).ready(function() {
$('#search-navlist li a').click(function() {
// alert($(this).text());
searchExhibitorsByAlphabet(this, $(this).text());
return false;
});
});
DEMO
You can also use delegate for better performance:
$(document).ready(function() {
$('#search-navlist').delegate('li a', 'click', function() {
// alert($(this).text());
searchExhibitorsByAlphabet(this, $(this).text());
return false;
});
});
Demo
Here is what you can do:
$(document).ready(function() {
$('#search-navlist').delegate("li", "click", function() {
searchExhibitorsByAlphabet(this, $(this).text());
return false;
});
});
And change your HTML to:
<ul id="search-navlist">
<li>A</li>
<li>B</li>
<li>C</li>
....
<li>Z</li>
</ul>
精彩评论