简体   繁体   English

javascript:将按钮替换为href

[英]javascript: Replacing button with a href

So i have this html/javscript code: 所以我有这个html / javscript代码:

<script type="text/javascript" src="includes/jquery/jquery.js"></script>
<button type="button">Click Me</button>
<p></p>
<?php $linkas= $_GET["linkas"]; ?>
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){

        $.ajax({
            type: 'POST',
            url: 'getmovies.php?linkas=<?php echo $linkas; ?>',
            success: function(data) {
                document.write(data);
    document.close();
            }
        });
});
});
</script>

How can i replace the button with text? 如何用文本替换按钮? i'v tried to replace the button.click with a a.click function but it still does not work. 我试图用a.click函数替换button.click,但仍然无法正常工作。 Thanks. 谢谢。

I am not entirely sure if I understood what you are asking. 我不确定我是否理解您的要求。 But as far as I understood you want to switch the button element with an a element. 但是据我了解,您想使用a元素切换button元素。

This can be done like that: 可以这样做:

$(document).ready(function(){
    $("button").click(function(){
        var href = "http://example.com"
        var content = $(this).text();
        $("button").replaceWith("<a href=\"" + href + "\">" + content + "</a>");
    });
    //... Your Code ...
});

Demo: 演示:

 $(document).ready(function(){ $("button").click(function(){ var href = "http://example.com" var content = $(this).text(); $("button").replaceWith("<a href=\\"" + href + "\\">" + content + "</a>"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button type="button">Click Me</button> 

Replace your <button/> with <a></a> and bind click event to element. <button/>替换为<a></a>并将click事件绑定到element。 Check this fiddle 检查这个小提琴

Try this 尝试这个

<script type="text/javascript" src="includes/jquery/jquery.js"></script>
<a href="#" id="my-link">Click Me</a>
<p></p>
<?php $linkas= $_GET["linkas"]; ?>
<script type="text/javascript">
$(document).ready(function(){
    $("#my-link").click(function(evt){
        evt.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'getmovies.php?linkas=<?php echo $linkas; ?>',
            success: function(data) {
                document.write(data);
    document.close();
            }
        });
});
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM