jquery hide text content in a tag, not the tag itself

北城以北 提交于 2019-12-23 08:27:17

问题


I have a slider using this html syntax:

<div id="theatre">
    <a class="sliderImg" href="01.jpg" />some-text</a>
    <a class="sliderImg" href="02.jpg" />another-description</a>
    <a class="sliderImg" href="03.jpg" />whatever</a>
    <a class="sliderImg" href="04.jpg" />whatever</a>
</div>

What I need to do is to hide the text of the a tags not the a tags themselves.

I got this but doesn't work.

var imgCaptions = $("#theatre a.sliderImg").html();
$(imgCaptions).hide();

I can't add a span because I use the content for some AJAX. The structure has to remain.

Many thanks for your help. Merry Xmas!


回答1:


I'd suggest:

a.sliderImg {
    color: transparent;
}

You could also use the user-select CSS property to prevent the text being selected:

a.sliderImg {
    color: transparent;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    user-select: none;
}

Or, possibly, use the unselectable attribute on the elements themselves:

<a unselectable="on" class="sliderImg" href="04.jpg">whatever</a>

Incidentally your HTML is malformed, the / should not be in the opening tag (that's only in the opening tag for void elements, such as input or img).

References:

  • user-select.



回答2:


You can remove the text simply by using the .text method:

$(".sliderImg").text('');

Fiddle: http://jsfiddle.net/J5QME/

If you need to store the text for use later, set it as a data attribute on the parent anchor:

$(".sliderImg").text(function(i,v){
    return $(this).data('originalText', v), '';
});

Fiddle: http://jsfiddle.net/J5QME/2/




回答3:


You can put extra tag ex. span around text inside a and hide the span some-text

$('#teathre span').hide();



回答4:


You can try this to hide just the text:

Live Demo: http://jsfiddle.net/yw8w2/1/

$('#theatre a.sliderImg').map(function(){ $(this).text(''); });


来源:https://stackoverflow.com/questions/14033200/jquery-hide-text-content-in-a-tag-not-the-tag-itself

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!