我是否使用了 $(this) 或 .click 不正确

Am I using $(this) or .click incorrectly?

本文关键字:this click 不正确 是否      更新时间:2023-09-26

我正在尝试构建一个简单的常见问题解答页面,其中包含在单击问题时向下和向上滑动的答案。当用户点击带有类"问题"的东西时,我希望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);