我需要使jQuery函数动态化(参数化)。目前我需要将每个表单id与jquery绑定,但我有超过一百个表单ID,因此重复代码对于相同的代码但不同的id将毫无意义。
例如:
以下是表格。它的id是“老鼠”
<form id="rat" action="" method="post">
<strong id="rating_title">Rate this: </strong>
<select name="rate">
<?php foreach (get_options() as $id => $title): ?>
<option value="<?php echo $id ?>" <?php echo $id==3 ? 'selected="selected"' : '' ?> /><?php echo $title ?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="Rate it!" />
</form>
以下是此表单附带的javascript
<script type="text/javascript">
$(function(){
$("#rat").children().not("select, #rating_title").hide();
// Create caption element
var $caption = $('<div id="caption"/>');
// Create stars
$("#rat").stars({
inputType: "select",
oneVoteOnly: true,
captionEl: $caption,
callback: function(ui, type, value)
{
// Display message to the user at the begining of request
$("#messages").text("Saving...").fadeIn(30);
// Send request to the server using POST method
/* NOTE:
The same PHP script is used for the FORM submission when Javascript is not available.
The only difference in script execution is the returned value.
For AJAX call we expect an JSON object to be returned.
The JSON object contains additional data we can use to update other elements on the page.
To distinguish the AJAX request in PHP script, check if the $_SERVER['HTTP_X_REQUESTED_WITH'] header variable is set.
(see: demo4.php)
*/
$.post("demo4.php", {rate: value}, function(json)
{
// Change widget's title
$("#rating_title").text("Average rating");
// Select stars from "Average rating" control to match the returned average rating value
ui.select(Math.round(json.avg));
// Update widget's caption
$caption.text(" (" + json.votes + " votes; " + json.avg + ")");
// Display confirmation message to the user
$("#messages").text("Rating saved (" + value + "). Thanks!").stop().css("opacity", 1).fadeIn(30);
// Hide confirmation message after 2 sec...
setTimeout(function(){
$("#messages").fadeOut(1000)
}, 2000);
}, "json");
}
});
// Since the <option value="3"> was selected by default, we must remove this selection from Stars.
$("#rat").stars("selectID", -1);
// Append caption element !after! the Stars
$caption.appendTo("#rat");
// Create element to use for confirmation messages
$('<div id="messages"/>').appendTo("#rat");
});
</script>
正如你可以看到它使用$(“#rat”)绑定到“rat”形式。
以同样的方式,我有大约100个具有不同ID的表单,我需要以类似的方式绑定每个表单...除了少数参数的更改。 例如:if form id-“rat2”then $(“#rat2”)... $(“#messages”)... etc
有没有办法可以封装上面的整个javascript / jquery代码,使其参数化。
请帮助!!!
答案 0 :(得分:1)
为每个“评级”表单添加一个类是否更有意义,只需将您的代码应用于该类的每个表单?
<form class="rating" id="???">
...
</form>
然后添加你的jQuery:
<script>
$(function(){
$('form.rating').each(function(){
//apply logic to each form (extract id's from "this" form as needed)
});
});
</script>