将href =#更改为javascript:

时间:2012-02-18 19:01:02

标签: javascript jquery html ajax

您好我之前询问过如何通过单击按钮加载div的内容(A url)而不是在页面加载之前加载这个代码作为答案:

<script type="text/javascript">
    function toggleDiv(id){
        if ($('#' + id).html() == '') {
            $.ajax({
                url: 'api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=SOMETHING&from=en&to=de&text=Hello', // your url to microsoft translator
                success: function(data) {
                    $('#' + id).html(data);
                },
                error: function() {
                    $('#' + id).html('The resource could not be loaded');
                }
            });
        }

        $('#' + id).toggle(); // Toggle div visibility
    }
</script>

<a href="#" onclick="toggleDiv('a')">Show/Hide Value</a>
<div id="a" style="display:none"></div>

首先,它无法正常运行并始终显示“资源无法加载”如果您输入类似(http://knowpersia.com/a.txt)的txt链接,它也无效。 其次,显示/隐藏值链接使用href =#和onclick系统来工作。当我在我的网站上使用它时,当我点击它时它会回到主页。有没有办法将其改为:

<a href="javascript:toggleDiv('a')">Show/Hide Value</a>

由于

1 个答案:

答案 0 :(得分:2)

您必须将id传递给toggleDiv()函数,并且您传递了一组对象 - &gt; toggleDiv('a') // Nop。 另外,如果你正在使用jQuery,我建议你摆脱那个丑陋的内联代码。然后,您可以将jQuery对象传递到函数中:

<a href="#" id="link">Show/Hide Value</a>
<div id="content"></div>

var toggleDiv = function($el) {
    if ($el.empty()) { // You can just use `empty()`
        $.ajax({
            url : 'api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=SOMETHING&from=en&to=de&text=Hello', // your url to microsoft translator
            success : function (data) {
                $el.html(data);
            },
            error : function () {
                $el.html('The resource could not be loaded');
            }
        });
    }
    $el.toggle(); // Toggle div visibility
};

$('#link').click(function(){ toggleDiv($('#content')); });
相关问题