设置<a> tag in javascript

时间:2015-10-21 12:49:30

标签: javascript attributes set

I'm trying to make changes in a code which shows, "title", using jQuery, from this JavaScript code:

<a id="photo" href="{%=file.url%}" title="{%=file.name%}" 
download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>

Using this "title="{%=file.name%}" it shows all the name of the file (containing image type - .jpg.)

I tried to add an id, as upper, and use:

document.getElementById("photo").setAttribute("title", "new title");

But I coudn't make it working. I would like add to the script:

 var title2="{%=file.name%}";
 title = (title2.slice(2, title2.length-4));    

To cut first 2 chars and 4 last. And then set it as a title.

Anyone can help?

Thanks!: )


<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}

<td style="padding-left:10px; display: inline-block;" class="template-download fade">
<div align="center" class="thumbnail" class="preview">
{% if (file.thumbnailUrl) { %}

<a id="photo" href="{%=file.url%}" title="{%=file.name%}" 
download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>           

 {% } %} </div>

<p class="name">
{% if (file.url) { %}
<a href="{%=file.url%}"  {%=file.thumbnailUrl?'data-gallery':''%}></a>

{% } %}</p></td>'{% } %}
</script>

I'am sending it couse, the < a > tag is in the JS, in the body, not in clean html, and maybe document.getElementsById, and document.getElementsByName will not work here? And I don't know from where I shoud call this ID. There are small bug in this JS (')but it works! :)

4 个答案:

答案 0 :(得分:0)

您可以使用此功能获得所需内容。

   var str = '';
//get name and put it in str here.
document.getElementsById("photo").title = str.slice(2, str.length-4);//str is the the name of the file.

或者您可以使用

获取所有链接

document.getElementsByName("link")[0].title = str.slice(2, str.length-4);

您的链接应该有name attr

<a href="#" name="link" tit......><img src="#"></a>

希望有所帮助!

答案 1 :(得分:0)

你能尝试这样吗

var  image = "picture.jpg"
var tiitle= image.substr(0, image.indexOf('.')); 
var tiitle = tiitle.substr(2,tiitle.length)
document.getElementById("photo").setAttribute("title", tiitle );

fiddler Link

答案 2 :(得分:0)

如果你正在使用jquery,就像你说的那样,试试这样:

<script>
$(document).ready(function () {
    var str = $('#photo').attr('title');
    $('#photo').attr('title',str.slice(2, str.length-4));
});
</script>

答案 3 :(得分:-1)

你能尝试给你的元素一个名字,所以你可以搜索它然后尝试:

document.getElementsByName("link")[0].title = "New title";

这可能不是您的最终解决方案,但如果可行,那么您的title属性可能包含一些无法处理的字符,但也许您可以告诉我们您的现有呼叫是否存在任何控制台错误。