我是否使用了 $(this) 或 .click 不正确
Am I using $(this) or .click incorrectly?
我正在尝试构建一个简单的常见问题解答页面,其中包含在单击问题时向下和向上滑动的答案。当用户点击带有类"问题"的东西时,我希望mytarget变成"#"+[该问题的id]+"answers",以便适当的答案向下滑动。
当我给它一个答案的 ID 时,切换幻灯片部分有效;我不确定我的 .click 函数是错误的,还是我使用 $(this),或者两者兼而有之。
$(document).ready(function() {
var qid = '';
var mytarget = '';
function toggleSlide() {
if ($(mytarget).css('display') == 'none') {
$(mytarget).slideDown(600, 'swing');
}
else if ($(mytarget).css('display') == 'block') {
$(mytarget).slideUp(600, 'swing');
}
};
$('.answer').hide();
$('.question').click(function() {
qid = $('this').id();
mytarget = '#' + qid + 'ans';
toggleSlide();
});
});
试试这个:
$(function() { // shorthand for $(document).ready()...
$('.answer').hide(); // preferably div.answer if they are all <div>s
$('.question').click(function() {
// no need to check what it currently is, use slideToggle
$('#' + this.id + 'ans').slideToggle(600, 'swing');
});
});
更改自:
$('this').id();
自:
$(this).attr('id')
-
this
是javascript中的一个关键字,而不是一个字符串。 - jQuery中没有
id
函数,你得到id与.attr('id')
。
id
是 DOM 元素的属性。所以你可以使用它:this.id
$('.question').click(function() {
qid = this.id;
mytarget = '#' + qid + 'ans';
toggleSlide();
});
不要做:qid = $('this').id();
do:不带单引号的qid = $(this).attr('id');
function toggleSlide(mytarget) {
if ($(mytarget).css('display')=='none'){
$(mytarget).slideDown(600, 'swing');}
else if ($(mytarget).css('display')=='block'){
$(mytarget).slideUp(600, 'swing');}
});
当你调用函数时,你应该传递参数计:
qid = $(this).id();
mytarget= '#' + qid + 'ans';
toggleSlide(mytarget);
相关文章:
- $(this).prop('property') vs. this.property
- Fancybox是否将Click事件静音
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- jQuery:.click(function(){(element),collapse('show',f
- 在另一个函数中使用变量this
- this.router在AngularJS 2中未定义
- reactjs this.refs vs document.getElementById
- JavaScript 中的嵌套函数和 “this” 关键字
- React+Meteor:this.ops返回未定义
- jQuery 'this' 跟随一个 .find click 函数
- jQuery: addClass and click function for this class
- Using $(this).find with .click() jQuery
- 我是否使用了 $(this) 或 .click 不正确
- jQuery — append(), then .click() + $(this).parent()
- 将焦点放在由 ng-click 调用的函数中的“this”元素上
- QWebElement评估JavaScript this.click()方法don'不起作用
- 无法得到this.mouse.click()"和casperjs一起工作
- Jquery - Using a function with .click and 'this'
- this.variable = NaN inside jquery's click()
- jQuery "this" inside click