2013-02-07 62 views
0

I have an image that has an InnerHTML for "a href" tag define in the .cs file as shown below.如何隱藏<a href> tag in InnerHTML

_divToolTipContainer.InnerHtml = "<a href=\"javascript:__doPostBack('" + btnItemThumbnail.ClientID.Replace("_", "$") + "','')\">" + 
              itemimage; 

Now what I want is to have this "a href" tag "hide" or "set visible to false" if the textbox is empty otherwise have this click-able.

My code is shown below, but its not working.

var oDivA1 = document.getElementById(oElementId); 

    if(val === undefined || val == null || val.length <= 0){   
     oDivA1.style.display = "none"; // not working 
    }else{ 
     oDivA1.style.display = "block"; // not working 
    } 

oDivA1.style.display = "none", this display none for the entire div not the "a href" tag only.

Is that possible?

Thanks

RJ

+0

您至少沒有關閉您的錨標記,也沒有關閉您顯示的代碼。 – tvanfosson

+0

'innerHTML' javascript方法不應該大寫,但'HTML'這個詞需要大寫。 –

回答

0

Use the firstChild property to get the inner element of the div, assuming that's all the HTML it contains as shown in your example.

var oDivA1 = document.getElementById(oElementId); 
var anchor = oDivA1 ? oDivA1.firstChild : null; 

if(anchor && (val === undefined || val == null || val.length <= 0)){   
    anchor.style.display = "none"; 
}else{ 
    anchor.style.display = "block"; 
} 

To prevent the link action

var handler = function(e) { e.preventDefault(); }; 

if(anchor && (val === undefined || val == null || val.length <= 0)){   
    anchor.addEventListener('click',handler,false); 
}else{ 
    anchor.removeEventListener('click',handler,false); 
} 

See https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener以瞭解有關瀏覽器兼容性和舊版瀏覽器的解決方法的信息。

+0

注意 - 這很大程度上取決於您顯示的確切標記,如果您將標記更改爲包含空格,則可能是瀏覽器。您可能需要使用jQuery等框架來進行調查。 – tvanfosson

+0

它工作正常,但整個圖像消失。我只是想讓這個href不可點擊的東西...有沒有更好的方法?謝謝 – user1306165

+0

@ user1306165 - 是的,您可以添加一個單擊處理程序來阻止默認操作,或者如果效果是永久性的,您可以移除錨點標記並用錨點標記的innerHTML替換div的內容。 – tvanfosson