Захватите содержимое текстового тега и замените его пользовательским текстом, используя JavaScript - PullRequest
0 голосов
/ 02 июня 2018

Привет. Ниже мой раздел svg

<g transform="translate(86.91003147398621,-21.306040772755345)" class="nv-label">
    <rect style="fill-opacity: 0; stroke-opacity: 0;"></rect>
    <text dy=".35em" style="fill-opacity: 1; fill: rgb(85, 85, 85); text-anchor: start;">Test Content</text>
</g>

Здесь мне нужно получить текст «Test Content» и заменить его каким-нибудь числом, как я могу сделать это с помощью javascript?

Любая помощь будет оценена.

Ответы [ 3 ]

0 голосов
/ 02 июня 2018

Это может помочь вам, посмотрите: D

function changeText(){
  var svg = document.querySelector('g');
  svg.lastElementChild.innerText = "hello World"
}
changeText();
<g transform="translate(86.91003147398621,-21.306040772755345)" class="nv-label">
    <rect style="fill-opacity: 0; stroke-opacity: 0;"></rect>
    <text dy=".35em" style="fill-opacity: 1; fill: rgb(85, 85, 85); text-anchor: start;">Test Content</text>
</g>
0 голосов
/ 02 июня 2018

Я думаю, что многие другие ответы пренебрегают, чтобы дать вам совет, как настроить SVG, чтобы вы могли позже легко найти свой текстовый элемент.

Обычный способ сделать это - датьтекстовый элемент id атрибут.Затем вы можете найти его, позвонив по номеру getElementById().

var textElem = document.getElementById("mytext");
textElem.textContent = "1234";
<svg>
  <text id="mytext" y="100">Test Content</text>
</svg>

Существуют и другие способы пометить свой элемент.Вы можете сделать это по class:

var allTextElems = document.getElementsByClassName("mytext");
for (var i=0; i< allTextElems.length; i++) {
  allTextElems.item(i).textContent = "1234";
};
<svg>
  <text class="mytext" y="75">Test Content</text>
  <text class="notmytext" y="100">Test Content</text>
  <text class="mytext" y="125">Test Content</text>
</svg>

Или вы можете сделать это, используя атрибут data:

var allTextElems = document.querySelectorAll('[data-key=mytext]');
allTextElems.forEach(function(item) {
  item.textContent = "1234";
});
<svg>
  <text data-key="mytext" y="75">Test Content</text>
  <text data-key="notmytext" y="100">Test Content</text>
  <text data-key="mytext" y="125">Test Content</text>
</svg>

Если по какой-то причине вы не можете изменить SVG, то следующим очевидным решением будет найти текстовый элемент, используя его положение в дереве DOM относительнок другим элементам.

// Select the first text element in the group which has class="two"
var textElem = document.querySelector("g.two text:first-child");
textElem.textContent = "1234";
<svg>
  <g class="one">
    <text y="50">Text in group 1</text>
  </g>
  <g class="two">
    <text id="mytext" y="100">Test Content</text>
    <text y="125">Other text in group 2</text>
  </g>
</svg>

Если вы не знаете, где в файле будет находиться целевой текст, вы будете знать только, что в нем содержится, тогда вам нужно будет выполнить поиск по всемтекстовые элементы, чтобы найти правильный текст.

// Select the SVG we want to search
// (This is an example of what you would need to do if you had more than one svg on the page)
var mySvg = document.querySelector("#mysvg");
// Find all the text elements in that svg
var allTextElems = document.querySelectorAll("text");
// Check all the text elements found, and if they contain our text
// then replace it with the new text.
allTextElems.forEach(function(item) {
  if (item.textContent === "Test Content") {
    item.textContent = "1234";
  }
});
<svg id="mysvg">
  <g class="one">
    <text y="50">Text in group 1</text>
  </g>
  <g class="two">
    <text id="mytext" y="100">Test Content</text>
    <text y="125">Other text in group 2</text>
  </g>
</svg>
0 голосов
/ 02 июня 2018

Как вы упомянули, есть несколько тегов g, вы можете использовать document.querySelectorAll('g text')[1];, чтобы получить ссылку на элемент второго text внутри тега g, а затем изменить значение с помощью textContent.(ответ обновлен на основе комментария ОП)

var textElem = document.querySelectorAll('g text')[1];
textElem.textContent =  1111;  
<g transform="translate(86.91003147398621,-21.306040772755345)" class="nv-label">
    <rect style="fill-opacity: 0; stroke-opacity: 0;"></rect>
    <text dy=".35em" style="fill-opacity: 1; fill: rgb(85, 85, 85); text-anchor: start;">Test Content</text>
</g>
<br/>
<g transform="translate(86.91003147398621,-21.306040772755345)" class="nv-label">
    <rect style="fill-opacity: 0; stroke-opacity: 0;"></rect>
    <text dy=".35em" style="fill-opacity: 1; fill: rgb(85, 85, 85); text-anchor: start;">Test Content</text>
</g>
<br/>
<g transform="translate(86.91003147398621,-21.306040772755345)" class="nv-label">
    <rect style="fill-opacity: 0; stroke-opacity: 0;"></rect>
    <text dy=".35em" style="fill-opacity: 1; fill: rgb(85, 85, 85); text-anchor: start;">Test Content</text>
</g>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...