2014-09-01 81 views
0

在最後一個問題中,我詢問了關於將變量提醒的信息。HTML作爲輸出JQuery

可以發現here

我修正了它,它現在可以工作。

隨着我從最後的答案中獲得的知識,我想做一個輸出<a> </a> 與變量在其中。

但我無法做到這一點。

我確實嘗試過各種類型的轉義,這些轉到了我的腦海。沒有幫助。

所以我會再次問你們:我該如何解決這個問題,以便正確打印出我的變量?

$('<a>' 
ID von '' + counter + '' 
XPosition '' + containerX + '', YPosition '' + ContainerY '</a>').appendTo($('#textuelledarstellung')); 

語境:

var counter = 0; 
$('#divfuerimage').on('click', function (evt) { 
    counter = counter + 1; 
    var containerX = evt.pageX - $(this).offset().left, 
    containerY = evt.pageY - $(this).offset().top; 
    alert('ID von' + counter + ' XPosition' + containerX + '' 
           , YPosition' + containerY); //this is working 

    $('<a>' 
    ID von '' + counter + '' 
    XPosition '' + containerX + '', YPosition '' + ContainerY '</a>').appendTo($('#textuelledarstellung')); 
      //this not 
+0

請格式化和重新表述您的問題。 – Satpal 2014-09-01 11:56:17

回答

2

使用jQuery創建元素,並使用它的方法來設置您的數據。

使用

var htmlText = 'ID von' + counter + ' XPosition' + containerX + ', YPosition' + containerY; 
$('<a></a>') 
    .prop('id', YourId) 
    .prop('href', Url) 
    .html(htmlText) 
    .appendTo($('#textuelledarstellung')); 
+1

這是處理插入HTML使用jQuery的正確方法。如果你使用字符串連接,你最終可能會得到一個難以維護並難以向其中添加另一個屬性的字符串怪物。如果使用上面的方法,那麼添加另一個屬性就很簡單了。 – Nzall 2014-09-01 11:57:56

0

試試這個:

var $link = $("<a>", { 
    "id" : "elementID",     // <a id="elementID"></a> 
    "class" : "elementClass",   // <a class="elementClass"></a> 
    "href" : "http:...",    // <a href="http:..."></a> 
    "html" : "<span>Text</span>",  // <a><span>text</span></a> 
    "text" : "Hello World" + " !",  // <a>Hello world</a> - this will replace previus HTML 
}); 

$("body").append($link); 

這將輸出:

<a id="elementID" class="elementClass" href="http:...">Hello World !</a> 
+0

這完全不是我想要的 – CodeFanatic 2014-09-01 12:15:22

+0

這是創建具有任何屬性的HREF的不同方式:) – Sams 2014-09-01 12:18:54