我正处于jQuery的开头,因此经历了一些练习......但我仍然坚持在DOM中有两个按钮的问题,每个按钮应该做不同的事情,当然。但是,我无法找到归因于不同操作的方法。有人可以帮忙吗? 这是HTML:
<div class="content">
<input type="text" class="my-input">
<button class="set-button">Set</button>
<button class="my-button">Add</button>
</div>
<h4>Output</h4>
<div id="output">
这就是我迄今为止所做的事情:
$('.content').click(function(){
var $input = $(this).find('input')
var input = $input.val();
$('#output').text(input)
console.log (input);
});
});
问题显然在于我没有调用特定的按钮来读取输入 - 我只是无法弄清楚将按钮的选择器放在哪里或者至少如果我做了代码没有工作了。可能看起来很傻,但我还在学习。 非常感谢提前!!
答案 0 :(得分:1)
您正在致电
$('.content').click(function(){}
但是类.content
是一个包装器..它包装了整个div
您应该使用按钮标记set-button
和my-button
中的选择器来点击后触发该功能
现在你有两个不同的类,所以你应该创建两个函数
$('.set-button').click(){/* logic */}
$('.my-button').click(/* logic */){}
很清楚吗?
答案 1 :(得分:1)
这可能对你有帮助。我们在按钮上创建了一个eventlistener。
$(this) - 是我们点击的元素。我们从这个元素中搜索同一父元素中的输入字段。保存我们的价值并将其附加到目标中。
$('.button-action').on('click', function(e) {
// we prevent the standard behaviour
e.preventDefault();
//we search in this context the input element to save the value
var inputText = $(this).parent('.content').find('.my-input').val();
// we save the target in Element in a value
var $target = $('#output');
// we ask what class the button has
if($(this).hasClass('set-button')) {
// we delete all child from target
$target.empty();
// we set the text of target with our input value
$target.text(inputText);
} else if($(this).hasClass('add-button')) {
// we append the input value to the target
$target.append(inputText);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<input type="text" class="my-input">
<button class="button-action set-button">Set</button>
<button class="button-action add-button">Add</button>
</div>
<h4>Output</h4>
<div id="output"></div>
&#13;