[英]Setting the title attribute of an <a> tag in javascript
我正在嘗試使用 jQuery 從此 JavaScript 代碼更改顯示“標題”的代碼:
<a id="photo" href="{%=file.url%}" title="{%=file.name%}"
download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>
使用這個“ title="{%=file.name%}
"它顯示了文件的所有名稱(包含圖像類型 - .jpg。)
我嘗試添加一個 id,作為上層,並使用:
document.getElementById("photo").setAttribute("title", "new title");
但我無法讓它發揮作用。 我想添加到腳本中:
var title2="{%=file.name%}";
title = (title2.slice(2, title2.length-4));
剪切前 2 個字符和最后 4 個字符。 然后將其設置為標題。
任何人都可以幫忙嗎?
謝謝!: )
<!-- 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>
我發送它的原因是,< a > 標簽在 JS 中,在正文中,而不是在干凈的 html 中,也許 document.getElementsById 和 document.getElementsByName 在這里不起作用? 我不知道我應該從哪里調用這個 ID。 這個JS(')中有一個小錯誤,但它有效! :)
你可以通過使用它來實現你想要的。
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>
希望有幫助!
你可以這樣試試嗎
var image = "picture.jpg"
var tiitle= image.substr(0, image.indexOf('.'));
var tiitle = tiitle.substr(2,tiitle.length)
document.getElementById("photo").setAttribute("title", tiitle );
小提琴手鏈接
如果你正在使用 jquery,就像你說的那樣,試試這樣:
<script>
$(document).ready(function () {
var str = $('#photo').attr('title');
$('#photo').attr('title',str.slice(2, str.length-4));
});
</script>
您可以嘗試為您的元素命名,以便您可以搜索它,然后嘗試:
document.getElementsByName("link")[0].title = "New title";
這可能不是您的最終解決方案,但如果可行,那么您的 title 屬性可能包含一些它無法處理的字符,但也許您可以告訴我們您現有的調用是否存在任何控制台錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.