2014-09-01 37 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