[英]add a html link button in javascript
我现在还很年轻,所以请多多包涵。 我正在制作一个网站,并且正在尝试在javascript中创建html链接输出。 我目前正在尝试这种方法,但是无法正常工作? 我正在尝试更改“神话”以显示此文本并添加链接。
我在其中尝试添加按钮的javascript代码是
document.getElementById('mything').innerHTML = place.name+' '+' <button id="edit" type = "button" class = "btn btn-link">(edit)</button>';
按钮的位是
$('#mything').on('click', function() {
$('#stuff2').hide();
})
我希望我把这个正确吗? 谢谢
使用您的代码,就会发生这种情况。 我已经注释了代码。 这是您期望发生的事情吗?
// Not sure what the place.name was coming from, // created a stub object to field that. place = { name: "Foo" }; // USe this to create the button, then create the // event listener ON the button. // This uses the browser getElementById... document.getElementById('mything').innerHTML = place.name+' '+' <button id="edit" type = "button" class = "btn btn-link">(edit)</button>'; // ...while the listener uses jquery to select the // element. On clicking, I toggle. $('#mything').on('click', function() { $('#stuff2').toggle(); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mything"> </div> <div id="stuff2"> <p>Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Curabitur aliquet quam id dui posuere blandit. Nulla porttitor accumsan tincidunt.</p> <p>Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Vivamus suscipit tortor eget felis porttitor volutpat. Nulla porttitor accumsan tincidunt. Vivamus suscipit tortor eget felis porttitor volutpat.</p> </div>
这是我尝试说明我认为您正在获得的结果:
var place = { name: 'Japan' }; var span = document.getElementById('mything'); span.innerHTML = place.name + ' <button id="edit" data-place="' + place.name + '">(edit)</button>'; span.querySelector('button').addEventListener('click', function(e){ var place = this.getAttribute('data-place'); alert(place); });
<span id="mything"></span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.