好的,我在页面上有多个表单,区别在于他们的id
,每个表单都有一个父框,所有这些框都有不同的id
。
其中一个框的html:
<div class="center-block" id="box2">
<form action="/login" id="form2" method="post" novalidate="novalidate">
<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="2">
<input id="Name" name="Name" type="hidden">
<input type="submit" value="Submit">
</form>
</div>
我使用ajax提交表单,我想要做的是找到提交表单的框的id
。
这是剧本:
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function () {
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Here I would like to alert the id of the parent box.
//Something like this:
alert($(this).closest('div').attr('id'));
//Which returns undefined
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});
</script>
知道我该怎么做吗?
答案 0 :(得分:5)
$(this)
无法成功回调。 $(this)
是相对的,<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function () {
var curr_form = $(this);
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Here I would like to alert the id of the parent box.
//Something like this:
curr_form.closest('div').attr('id')
//Which returns undefined
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});
</script>
的范围将成功回调。你需要先分配一个变量&amp;然后在成功回调中使用它
public class settings_tab extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
return inflater.inflate(R.layout.activity_settings_tab, container, false);
}
}
答案 1 :(得分:1)
只需使用JQuery parent() 方法:
alert($(this).parent().attr('id'));
此外,正如其他人所指出的,当您在成功回调中使用this
时form
没有指向this
时,您会遇到另外一个问题。您应该缓存该值,然后使用缓存变量。您可以详细了解$(document).ready(function() {
$('form').submit(function () {
// Cache the object that "this" is bound to because
// in the success function, the invocation context
// changes and "this" won't point to the same object
// it does now.
var theForm = this;
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Just use the JQuery parent() method with the cached object
$(theForm).parent().attr('id')
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});
在我的 in another post 的JavaScript中的工作原理。
user> (defn dissoc-by [f m] (->> m (filter #(f (first %))) (into {})))
#'user/dissoc-by
user> (dissoc-by #(.contains % "good") m)
{"good1" 1, "good2" 2}