我有两个具有相同ID但在alt属性中具有不同文本的按钮。单击按钮时,我需要该按钮的 alt文本加载到文本框中。我目前只是“未定义”
$(document).ready(function() {
$('button').on('click', function() {
var sentence = $('button').prop('alt');
var text = $('#the_box');
text.val(text.val() + sentence + ' ');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<h5 style="text-align:center;">
The buttons have alt="" text that needs to be added to the contents of the textbox when pressed.
</h5>
<div style="box-shadow:2px 2px 5px black; min-height:200px; padding:25px; margin:10px;">
<textarea id="the_box" class="form-control" rows="3"></textarea>
<button class="btn" id="hotlink" alt="I am very concerned.">Concerned</button>
<button class="btn" id="hotlink" alt="I am very happy.">Happy</button>
</div>
</div>
</div>
</div>
答案 0 :(得分:3)
试试这个,你需要使用attr
函数代替prop
和$(this)
代替$('button')
$(document).ready(function() {
$('button').on('click', function(e) {
var sentence = $(this).attr('alt');
var text = $('#the_box');
text.val(text.val() + sentence + ' ');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<h5 style="text-align:center;">
The buttons have alt="" text that needs to be added to the contents of the textbox when pressed.
</h5>
<div style="box-shadow:2px 2px 5px black; min-height:200px; padding:25px; margin:10px;">
<textarea id="the_box" class="form-control" rows="3"></textarea>
<button class="btn" id="hotlink" alt="I am very concerned.">Concerned</button>
<button class="btn" id="hotlink" alt="I am very happy.">Happy</button>
</div>
</div>
</div>
</div>
答案 1 :(得分:0)
您希望按钮具有唯一的ID,并使用$(this)访问单击的按钮。 alt也是HTML 属性
language_test_map = {'french': 1,
'italian': 2,
'chinese': 3,
'english': 4,
'russian': 5}
df['exam_id'] = df['exam'].map(language_test_map)
$(document).ready(function() {
$('button').on('click', function() {
var sentence = $(this).attr('alt');
var text = $('#the_box');
text.val(text.val() + sentence + ' ');
});
});
答案 2 :(得分:0)
您应该使用ID
在整个HTML页面中对元素进行唯一标识。要更好地使用alt
功能访问attr()
属性,prop()
用于retrieve property值(例如,选中状态的复选框)
更改HTML代码
<button class="btn hotlink" alt="I am very concerned.">Concerned</button>
<button class="btn hotlink" alt="I am very happy.">Happy</button>
所以,你的脚本将是
$(document).ready(function() {
$('document').on('click', '.hotlink', function() {
var sentence = $(this).attr('alt');
var text = $('#the_box');
text.val(text.val() +' '+ sentence + ' ');
});
});