问题
I'm running a really simple jQuery script to grab all emails selected by checkboxes in a table. The table looks like this:
<table>
<tbody>
<tr>
<td>
<input type="checkbox" value="MD5HASH" />
</td>
<td>
First Name
</td>
<td class="email">
Email Address
</td>
</tr>
</tbody>
</table>
My jQuery looks like this:
$("#submitButton").click(function() {
var output = [];
$("table tbody tr:has(input:checkbox:checked)").each(function() {
var email = $('td.email', $(this)).text();
if (validate(email) && output.indexOf(email) == -1)
output.push(email);
});
$("#emails").val(output.join(", "));
});
function validate(email) {
return /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/.test(email);
}
This fails miserably in IE, but works everywhere else.
- The
table tbody tr:has(input:checkbox:checked)
selector matches nothing. - The call to validate throws a
Object expected
error.
WHY!? Isn't jQuery designed to be cross-browser and portable?
回答1:
Internet Explorer (< 9) doesn't have Array.prototype.indexOf. Try using jQuery's $.inArray instead (it's cross browser and will actually use Array.prototype.indexOf
if it exists :-P).
if (validate(email) && $.inArray(email,output) == -1)
output.push(email);
回答2:
give the input a class and target it directly...
<table>
<tbody>
<tr>
<td>
<input class="emailchecked" type="checkbox" value="MD5HASH" />
</td>
<td>
First Name
</td>
<td class="email">
Email Address
</td>
</tr>
</tbody>
</table>
Then target the checked ones in your js like this:
$("#submitButton").click(function() {
var output = [];
$(".emailchecked ([checked='checked'])").each(function() {
var email = $('td.email', $(this)).text();
if (validate(email) && output.indexOf(email) == -1)
output.push(email);
});
$("#emails").val(output.join(", "));
});
function validate(email) {
return /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/.test(email);
}
回答3:
<table>
<tr><td><input type="checkbox" value=""/></td><td>one@gmail.com</td></tr>
<tr><td><input type="checkbox" value=""/></td><td>two@gmail.com</td></tr>
<tr><td><input type="checkbox" value=""/></td><td>three@gmail.com</td></tr>
<tr><td><input type="checkbox" value=""/></td><td>four@gmail.com</td></tr>
</table>
<input id="btnSubmit" type="button" value="Submit"/>
<div id="emails"></div>
<script type="text/javascript">
$('#btnSubmit').click(function(e){
var emails = [];
$('table').find('input').each(function() {
if ($(this).is(':checked'))
emails.push($(this).parent().next().text());
});
$("#emails").empty().html(emails.join(", "));
});
</script>
Since you have three columns instead of two, just walk the DOM for that row.
来源:https://stackoverflow.com/questions/7812866/why-cant-internet-explorer-run-this-simple-jquery