[英]add a html link button in javascript
I'm pretty young and new to here so please bear with me. 我现在还很年轻,所以请多多包涵。 I am making a site and I am trying to create html links output in javascript.
我正在制作一个网站,并且正在尝试在javascript中创建html链接输出。 I am currently trying this method but it is not working?
我目前正在尝试这种方法,但是无法正常工作? I am trying to change the 'mything' to show this text and add a link.
我正在尝试更改“神话”以显示此文本并添加链接。
The code in javascript where I try to add a button is 我在其中尝试添加按钮的javascript代码是
document.getElementById('mything').innerHTML = place.name+' '+' <button id="edit" type = "button" class = "btn btn-link">(edit)</button>';
The bit for button is 按钮的位是
$('#mything').on('click', function() {
$('#stuff2').hide();
})
I hope I have put this in right? 我希望我把这个正确吗? Thankyou
谢谢
Using your code, this is what happens. 使用您的代码,就会发生这种情况。 I've commented the code up.
我已经注释了代码。 Is this what you EXPECT to happen?
这是您期望发生的事情吗?
// 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>
Here's my attempt at illustrating what I think you're getting at: 这是我尝试说明我认为您正在获得的结果:
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.