javascript - 单击输入字段触发 jQuery 函数

标签 javascript jquery html css

我正在尝试创建一个可选列表,当您单击某个元素时,它会显示一个输入字段,您可以使用该字段来编辑描述,但在单击该元素之前,输入字段是隐藏的。

但是,当我选择一个元素然后单击输入字段时,它会取消选择该元素并且输入字段再次隐藏。

我重新创建了问题 here只有一个列表项。如何允许用户在不触发 jQuery 函数的情况下单击输入字段?

此外,用户将能够单击列表中的多个元素,因此我用第二个元素更新了 jsbin。

最佳答案

如果您不想更改输入的 html 排列,您可以阻止单击输入元素时将事件传播到其父元素,从而避免任何类切换。

您唯一需要的就是这个。

$('.fund input').click(function(e) {
  e.stopPropagation();
});

这是工作示例

$('.fund').click(function() {
  $(this).toggleClass('selected');
});
$('.fund input').click(function(e) {
  e.stopPropagation();
});
* {
  font-family: 'Lato', sans-serif;
}
.fund {
  background-color: #fff;
  width: 500px;
  border: 1px solid #444;
  height: 50px;
  padding: 0 10px;
  border-radius: 3px;
}
.fund:hover {
  background-color: #efefef;
  cursor: pointer;
}
.fund .description,
.fund .alt-description {
  width: 50%;
  float: left;
}
.fund .description {
  line-height: 50px;
  font-size: 12px;
  letter-spacing: 1px;
  text-transform: uppercase;
  font-weight: 700;
  color: #555;
}
.fund .alt-description {
  visibility: hidden;
  line-height: 50px;
  font-size: 14px;
}
.fund .alt-description input {
  height: 30px;
  font-size: 12px;
}
.fund.selected {
  border: 1px solid #00cc00;
}
.fund.selected .description {
  color: #00cc00;
}
.fund.selected .alt-description {
  visibility: visible;
}
<!DOCTYPE html>
<html>

<head>
  <meta name="description" content="[be able to click in input but don't toggle div]">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'>
  <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
  <title>JS Bin</title>
</head>

<body>
  <div class='fund'>
    <div class='description'>
      Fund Name
    </div>
    <div class='alt-description'>
      Description:
      <input type='text' value='Fund Name'>
    </div>
  </div>
</body>

</html>

关于javascript - 单击输入字段触发 jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461398/

相关文章:

javascript - 将背景图像缩放到用户的浏览器大小

javascript - 如何在离线 Web 应用程序中存储 250mb 的数据库

javascript - 标准伪随机数生成器无法承受 jquery.js 文件中 math.random() 函数的加密攻击

javascript - 如何将可自定义的颜色更改框下载为带有背景图像的图像?

html - 如何基于移动设备的用户代理替换超链接

javascript - 脚本组织模式(MVC + jQGrid)

javascript - jquery 执行声明的函数而不需要我点击

php - 使用 Jquery、PHP、Mysql 进行 Ajax 分页

javascript - 在 Javascript 中将多个对象添加到数组中 n 次

javascript - 重新排列区域内的图 block