Insira um link usando CSS
Pergunta
Estou com manutenção manual de um documento HTML e estou procurando uma maneira de inserir automaticamente um link em torno do texto em uma tabela. Deixe -me ilustrar:
<table><tr><td class="case">123456</td></tr></table>
Gostaria de fazer automaticamente todos os texto em um TD com a classe "case" um link para esse caso em nosso sistema de rastreamento de bugs (que, aliás, é Fogbugz).
Então, gostaria que esse "123456" fosse alterado para um link deste formulário:
<a href="http://bugs.example.com/fogbugz/default.php?123456">123456</a>
Isso é possível? Eu brinquei com o: Antes e: After pseudo-elementos, mas não parece haver uma maneira de repetir o número do caso.
Solução
Não de uma maneira que funcione entre os navegadores. Você poderia, no entanto, fazer isso com algum javascript relativamente trivial.
function makeCasesClickable(){
var cells = document.getElementsByTagName('td')
for (var i = 0, cell; cell = cells[i]; i++){
if (cell.className != 'case') continue
var caseId = cell.innerHTML
cell.innerHTML = ''
var link = document.createElement('a')
link.href = 'http://bugs.example.com/fogbugz/default.php?' + caseId
link.appendChild(document.createTextNode(caseId))
cell.appendChild(link)
}
}
Você pode aplicá -lo com algo como onload = makeCasesClickable
, ou simplesmente incluí -lo no final da página.
Outras dicas
aqui está um jQuery Solução específica para o seu HTML postado:
$('.case').each(function() {
var link = $(this).html();
$(this).contents().wrap('<a href="example.com/script.php?id='+link+'"></a>');
});
Em essência, sobre cada elemento .Scase, agarrará o conteúdo do elemento e os jogará em um link envolvido em torno dele.
Não é possível com o CSS, além disso, não é isso que o CSS é de forma alguma. JavaScript ou lado do servidor do lado do cliente (INSERIR LANGUEM DE ESCOLHA) é o caminho a percorrer.
Eu não acho que seja possível com o CSS. O CSS deve afetar apenas a aparência e o layout do seu conteúdo.
Parece um trabalho para um script PHP (ou algum outro idioma). Você não deu informações suficientes para eu saber a melhor maneira de fazê -lo, mas talvez algo assim:
function case_link($id) {
return '<a href="http://bugs.example.com/fogbuz/default.php?' . $id . '">' . $id . '</a>';
}
Depois mais tarde no seu documento:
<table><tr><td class="case"><?php echo case_link('123456'); ?></td></tr></table>
E se você deseja um arquivo .html, basta executar o script da linha de comando e redirecionar a saída para um arquivo .html.
Você pode ter algo assim (usando JavaScript). Lado de dentro <head>
, tenho
<script type="text/javascript" language="javascript">
function getElementsByClass (className) {
var all = document.all ? document.all :
document.getElementsByTagName('*');
var elements = new Array();
for (var i = 0; i < all.length; i++)
if (all[i].className == className)
elements[elements.length] = all[i];
return elements;
}
function makeLinks(className, url) {
nodes = getElementsByClass(className);
for(var i = 0; i < nodes.length; i++) {
node = nodes[i];
text = node.innerHTML
node.innerHTML = '<a href="' + url + text + '">' + text + '</a>';
}
}
</script>
E então no final de <body>
<script type="text/javascript" language="javascript">
makeLinks("case", "http://bugs.example.com/fogbugz/default.php?");
</script>
Eu testei e funciona bem.
I know this is an old question, but I stumbled upon this post looking for a solution for creating hyperlinks using CSS and ended up making my own, could be of interest for someone stumbling across this question like I did:
Here's a php function called 'linker();'that enables a fake CSS attribute
connect: 'url.com';
for an #id defined item. just let the php call this on every item of HTML you deem link worthy. the inputs are the .css file as a string, using:
$style_cont = file_get_contents($style_path);
and the #id of the corresponding item. Heres the whole thing:
function linker($style_cont, $id_html){
if (strpos($style_cont,'connect:') !== false) {
$url;
$id_final;
$id_outer = '#'.$id_html;
$id_loc = strpos($style_cont,$id_outer);
$connect_loc = strpos($style_cont,'connect:', $id_loc);
$next_single_quote = stripos($style_cont,"'", $connect_loc);
$next_double_quote = stripos($style_cont,'"', $connect_loc);
if($connect_loc < $next_single_quote)
{
$link_start = $next_single_quote +1;
$last_single_quote = stripos($style_cont, "'", $link_start);
$link_end = $last_single_quote;
$link_size = $link_end - $link_start;
$url = substr($style_cont, $link_start, $link_size);
}
else
{
$link_start = $next_double_quote +1;
$last_double_quote = stripos($style_cont, '"', $link_start);
$link_end = $last_double_quote;
$link_size = $link_end - $link_start;
$url = substr($style_cont, $link_start, $link_size); //link!
}
$connect_loc_rev = (strlen($style_cont) - $connect_loc) * -1;
$id_start = strrpos($style_cont, '#', $connect_loc_rev);
$id_end = strpos($style_cont,'{', $id_start);
$id_size = $id_end - $id_start;
$id_raw = substr($style_cont, $id_start, $id_size);
$id_clean = rtrim($id_raw); //id!
if (strpos($url,'http://') !== false)
{
$url_clean = $url;
}
else
{
$url_clean = 'http://'.$url;
};
if($id_clean[0] == '#')
{
$id_final = $id_clean;
if($id_outer == $id_final)
{
echo '<a href="';
echo $url_clean;
echo '" target="_blank">';
};
};
};
};
this could probably be improved/shortened using commands like .wrap() or getelementbyID()
because it only generates the <a href='blah'>
portion, but seeing as </a>
disappears anyway without a opening clause it still works if you just add them everywhere :D