Pass Parameter to Custom jQuery Function
Here's what I have so far:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript"&开发者_如何转开发gt;
$(document).ready(function() {
$("#weight").change(onSelectChange);
});
function onSelectChange(){
var selected = $('#weight').val();
$.post("tship.php", {weight: selected},
function(data){
$("#ship").html(data.ret_html);
}, "json");
}
</script>
</head>
<body>
<select id="weight">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<br />
<div id="ship">
</div>
</body>
</html>
I want to change it so that onSelectChange accepts a single parameter. I need to be able to call the function for other events as well - not only when the select box value changes. Here is my attempt, not working:
<script type="text/javascript">
$(document).ready(function() {
$("#weight").change(onSelectChange($('#weight').val()));
});
function onSelectChange(parm){
$.post("tship.php", {weight: parm},
function(data){
$("#ship").html(data.ret_password);
}, "json");
}
</script>
Try this:
$("#weight").change(function(){
onSelectChange($(this).val());
});
You should add another function:
$("#weight").change(function(){
onSelectChange($('#weight').val());
}); //close the anonymous function
Note that in your original code you've passed onSelectChange
as a reference, you didn't start it - onSelectChange()
. With the code as it is, you start the function once instead of binding it.
You were calling a function within another function, so I think that if you amend your code to the following it should work okay (assuming your onSelectChange()
function works properly:
$(document).ready(function() {
$("#weight").change(
function() {
$(this).onSelectChange($('#weight').val()));
}
);
});
You can't do that, the onSelectChange gets called by jQuery's change function so it chooses what params to pass.
In your case however, this is simple, jQuery will bind 'this' to the item that you've applied that event handler to, so you can reference that value in your onSelectChange using:
$(this).val();
精彩评论