javascript - onclick 函数关闭 'help window' 不工作

标签 javascript jquery html css

我已经在将显示帮助窗口的表单中设置了一个 div,我想在右上角设置一个“X”,并使用 onclick 函数关闭窗口。这个 div 位于我的 HTML 的底部,就在结束 body 标记之前,这是正确的位置吗? 请注意,我想用 display:none 标签来做这件事,而不是 show() 或 hide() HTML

<div id="personalhelp"><p class="x"><a href="" onclick="close()">x</a></p>
<p class="help">Your personal information is needed to ensure we provide the most 
relevant information and options for you. We will never sell your personal
 information to third parties for any reason.</p>
<p class="help">Please fill in all required fields, 
these are identified with an asterisk (*)</p>
</div>

函数(Jquery)

function close() {
    var getid = $(this).parent.attr('id');
   console.log(getid);
   $(getid).css("display", "none");
}

CSS

#personalhelp {
    position: fixed;
    right: 10%;
    top: 10%;
    max-width: 60%;
    display: block;
    background-color: #D3D3D3;
    color: #000;
    margin: 5px auto;
    border: 2px solid #000;
    display: block;
}

.x {
    position: absolute;
    right: 1%;
    top:1%;
    padding: 1px;
    margin: 0 auto;
}
.help {
    padding: 10px;
}

最佳答案

您的close() 方法不知道this 是什么。 jQuery 有它自己的 click() 函数,您应该使用它并避免在您的 HTML 中使用 onclick="..."。只需这样做:

$( ".x" ).click(function() {
    $(this).parent().hide();
});

当然,除了 hide() 之外,您还可以通过其他方式处理“关闭”。这是关于 click() 调用的。

这是一个运行示例:

$(".x").click(function() {
  $(this).parent().hide();
});
#personalhelp {
  position: fixed;
  right: 10%;
  top: 10%;
  max-width: 60%;
  display: block;
  background-color: #D3D3D3;
  color: #000;
  margin: 5px auto;
  border: 2px solid #000;
  display: block;
}

.x {
  position: absolute;
  right: 1%;
  top: 1%;
  padding: 1px;
  margin: 0 auto;
}

.help {
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="personalhelp">
  <p class="x"><a href="" onclick="close()">x</a></p>
  <p class="help">Your personal information is needed to ensure we provide the most relevant information and options for you. We will never sell your personal information to third parties for any reason.</p>
  <p class="help">Please fill in all required fields, these are identified with an asterisk (*)</p>
</div>

关于javascript - onclick 函数关闭 'help window' 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46583514/

相关文章:

javascript - 如何使用javascript制作平滑的滚动效果

javascript - 如何跟踪/排除 <div> 或 <class> 属性的故障?

javascript - jQuery - 粘性元素与页脚重叠,如何避免?

java - 可以让内网用户通过浏览器截取当前页面吗?

javascript - 在 PHP 页面上加载富文本编辑器 (TinyMCE) 的 jquery 插件时显示加载动画

javascript - 如何获取动态生成元素的id属性?

javascript - 替换 AJAX 响应的一部分

javascript - 使用嵌套的div上下滑动

javascript - jQuery if input[type ="radio"] before clickable label hasn't attribute "checked"then do NOT add it,否则什么都不做

javascript - 如何获取我正在单击的按钮的 ID