0

我有一个切换功能。当它第一次被触发时,链接没有激活,因为返回 false - 这很好。

但是切换后链接确实会触发!我也不需要。请问有什么帮助吗?

function viewSHowHide() {

if (document.getElementById("viewSHowHide").innerHTML=="Hide Question") {
document.getElementById("viewSHowHide").innerHTML="View Question";
HideQ();

} else {
document.getElementById("viewSHowHide").innerHTML="Hide Question";
viewQ();
}

} 

HTML

<a title="View Question" id="viewSHowHide" onclick="viewSHowHide(); return false" href="">View Question</a>
4

3 回答 3

1

这是您尝试执行的操作的一个工作示例http://jsfiddle.net/ericjbasti/fnd9C/

我将其切换为 a<span>这样我就不必与链接默认要做的事情作斗争,并稍微清理了代码。

HTML:

<span title="View Question" id="viewSHowHide" onclick="viewSHowHide();">View Question</span>

JavaScript:

viewSHowHide = function(){
    var showHide=document.getElementById("viewSHowHide");
    if (showHide.innerHTML=="Hide Question") {
        showHide.innerHTML="View Question";
        HideQ();
    } else {
        showHide.innerHTML="Hide Question";
        viewQ();
    } 
} 
于 2013-08-18T18:58:36.067 回答
1

尝试href="javascript:void(0)"使用

<a title="View Question" id="viewSHowHide" onclick="viewSHowHide(); return false" href="javascript:void(0)">View Question</a>
于 2013-08-18T19:10:09.427 回答
0

I think...

All You Need

if (event.preventDefault) { //check if browser supports preventDefault
    event.preventDefault();
} else { //if no support -> IE lte 8
    event.returnValue = false;
}

or shorthand: event.preventDefault ? event.preventDefault() : event.returnValue = false;

wrap it in a function for faster usage e.g. :

<a href="#something" onclick="prevent();">click prevent</a>

<script>
prevent = function() { // in this case no need to pass 'event'
    event.preventDefault ? event.preventDefault() : event.returnValue = false;
    console.log('event prevented :)');
}
</script>

Why all modern browsers support event.preventDefault, but IE supports it from v9 for older IE versions (this is what e.g. jQuery uses) you hook up to the returnValue of an event.

*jQuery Code for reference

jQuery.Event.prototype = {
[...]
preventDefault: function() {
    var e = this.originalEvent;

    this.isDefaultPrevented = returnTrue;
    if ( !e ) {
        return;
    }

    // If preventDefault exists, run it on the original event
    if ( e.preventDefault ) {
        e.preventDefault();

    // Support: IE
    // Otherwise set the returnValue property of the original event to false
    } else {
        e.returnValue = false;
    }
},
[...]

I hope i didn't make any mistakes here ;) Good Luck...

于 2013-12-05T18:08:08.547 回答