问题
I have some radio buttons in a form:
<div id="data_id-block">
<dt id="data_id-label"><label class="required">Data</label></dt>
<dd id="data_id-element">
<label for="data_id-1">
<input type="radio" name="data_id" id="data_id-1" value="1" />test 1
</label><br />
<label for="data_id-2">
<input type="radio" name="data_id" id="data_id-2" value="2" />test 2
</label><br />
<label for="data_id-4">
<input type="radio" name="data_id" id="data_id-4" value="4" /> Test Data
</label><br />
<label for="data_id-5">
<input type="radio" name="data_id" id="data_id-5" value="5" /> Second Test Data
</label><br />
<label for="data_id-6">
<input type="radio" name="data_id" id="data_id-6" value="6" />Unassigned
</label>
</dd>
I'm trying to display a tooltip when a user hovers over the label of the radio button. I can do this but I also want to get whatever is in the 'value' property of the radio button. My attempts to this resulted in only the 'value' of the radio button being returned regardless of which radio button was hovered over.
Appreciate the help.
回答1:
//this is just one way to register to the window.onLoad event in jQuery, i prefer it's readability for what is going on
$(document).ready(function(){
//$("something", "something else") - 'Something Else' limits where jQuery searches for 'something'
// .hover( function A , function B ) - function A is the mouseover event, function B is the mouseleave event
// function(event){} for All events, jQuery will always pass an "event" parameter if you ask for it on the window .event() registration. cool stuff you can do with jQuery's "event" parameter can be found here in the references below.
$("label", "#data_id-element").hover(function(event){
// $(this) jQuery'itize the html Element the user hovered into
// .attr("for") - get the value of the 'for' attribute
// $("#" + whatever) - get whatever this is by its id='' attribute
// .val() - get the value of whatever this is
var radioValue = $("#"+$(this).attr("for")).val();
},
function(event){
// $(this) jQuery'itize the html Element the user hovered out of
// .attr("for") - get the value of the 'for' attribute
// $("#" + whatever) - get whatever this is by its id='' attribute
// .val() - get the value of whatever this is
var radioValue = $("#"+$(this).attr("for")).val();
});
});
回答2:
If I've understood you correctly, you want to get the value of the radio button associated with a label
, when you hover over the label
. If that's the case, try something like this:
$("label").mouseover(function() {
var radioButtonValue = $(this).find("input").val();
});
Here's a working example.
来源:https://stackoverflow.com/questions/7838646/displaying-a-tooltip-when-user-hovers-on-label-of-radio-button-in-jquery